There are many ways to calculate the Fibonacci number, you can use the definition and calculate them sequentially. However, it seems to me the most productive approach is to first create the function fibanchi()
, which calculates an arbitrary Fibonacci number by its number in the sequence. The fastest way to solve this particular problem is the Binet formula.
<?php function fibanchi($n) { return round((((1 + sqrt(5)) / 2) ** $n - ((1 - sqrt(5)) / 2) ** $n) / sqrt(5)); }
However, not only is the formula itself approximate, for large values of the Fibonacci number, you can quickly go beyond the boundaries of both integer and floating point numbers. If the goal is the highest values of Fibonacci numbers and accuracy, you can organize calculations in the array directly by definition - long, but the values obtained will be very accurate (in this case, you can wipe numbers 2000 and higher, which are obviously not available when calculating using the Binet formula using scalar types).
<?php function fibanchi($n) { // К-во разрядов $digit = intval($n / 4) + 5; $result = ''; $a1 = []; $a2 = []; $a3 = []; $a1[0] = 1; $a2[0] = 1; for($j = 2; $j < $n; $j++) { for($i = 0; $i < $digit; $i++) { $a1[$i] = isset($a1[$i]) ? $a1[$i] : 0; $a2[$i] = isset($a2[$i]) ? $a2[$i] : 0; $b = intval(($a1[$i] + $a2[$i])/10); $a3[$i] = $a1[$i] + $a2[$i] - $b * 10; isset($a1[$i + 1]) ? $a1[$i + 1] += $b : $a1[$i + 1] = $b; } for($i = 0; $i < $digit; $i++) { $a1[$i] = $a2[$i]; $a2[$i] = $a3[$i]; $a3[$i] = 0; } } $flg = false; for($i = count($a2) - 1; $i >= 0; $i--) { if($a2[$i] >= 1) $flg = true; if($flg) $result .= $a2[$i]; } return $result; }
To output a sequence, you can use the loop
<?php for($i = 0; $i < 20; $i++) { echo fibanchi($i)."<br />"; }