Finding the next Fibonacci number

I need to find the (next) Fibonacci number given by an integer N. So, let's say I have n = 13, and I need to print the next Fibonacci number, which is 21, but how to do it? How can I find the previous number that is summed to form it?

I mean, I could easily create a for / while loop that returns a Fibonacci sequence, but how can I find the next number by getting the previous one.

<?php

$n = 13;

while($n < 1000) {

    $n = $x + $y; 
    echo($n."<br />"); 
    $x = $y;
    $y = $n;
}
?>
+4
source share
2 answers

Using a loop, you can save the values ​​in an array that can immediately stop one key after finding the selected number in the previous key value.

function getFib($n) {

   $fib = array($n+1);       // array to num + 1
   $fib[0] = 0; $fib[1] = 1; // set initial array keys
   $i;

   for ($i=2;$i<=$n+1;$i++) {
      $fib[$i] = $fib[$i-1]+$fib[$i-2];
        if ($fib[$i] > $n) { // check if key > num 
            return $fib[$i];
            }
        }
    if ($fib[$i-1] < $n) {   // check if key < num
        return $fib[$i-1] + $n;
    }
    if ($fib[$i] = $n-1) {   // check if key = num
        return $fib[$i-1] + $fib[$i-2];
    } 
    if ($fib[$i-1] = 1) {    // check if num = 1
        return $n + $n;
    }
}

$num = 13;
echo "next fibonacci number = " . getFib($num);

, , , , downvoting, , .

+1

Binet:

          n          -n
F(n) = phi   - (-phi)
       ---------------
          sqrt(5)

phi - (( 1 + sqrt(5) ) / 2) ~= 1.61803...

n- .

+4

Source: https://habr.com/ru/post/1544937/


All Articles