Finding next fibonacci number

主宰稳场 提交于 2020-01-03 13:32:36

问题


I need to find a (the next) fibonacci number given a integer N. So let's say I have n = 13 and I need to output the next fibonacci number which is 21 but how do I do this? How can I find the previous number that summed up to form it?

I mean I could easily come up with a for/while loop that returns the fibonacci sequence but how can I find the next number by being given the previous one.

<?php

$n = 13;

while($n < 1000) {

    $n = $x + $y; 
    echo($n."<br />"); 
    $x = $y;
    $y = $n;
}
?>

回答1:


Using a loop you could store the values in an array that could stop immediately one key after finding the selected number in the previous keys 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);

Please note that I haven't tested this out and the code could be optimized, so before downvoting consider this serves only as a concept to the question asked.




回答2:


You can use Binet's Formula:

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

where phi is the golden ratio (( 1 + sqrt(5) ) / 2) ~= 1.61803...

This lets you determine exactly the n-th term of the sequence.




回答3:


You can do it in 1 step:

phi = (1+sqrt(5))/2

next = round(current*phi)

(Where round is a function that returns the closest integer; basically equivalent to floor(x+0.5))

For example, if your current number is 13: 13 * phi = 21.034441853748632, which rounds to 21.



来源:https://stackoverflow.com/questions/24267939/finding-next-fibonacci-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!