我需要找到一个给出整数N的(下一个)斐波那契数.因此,假设我有n = 13,我需要输出下一个斐波那契数(即21),但是我该怎么做呢?我怎样才能找到以前的总和形成数字?
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?
我的意思是我可以很容易地提出一个for/while循环,该循环返回斐波那契数列,但是如何通过给出前一个来找到下一个数.
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; } ?> 推荐答案使用循环,您可以将值存储在一个数组中,该数组可以在找到先前键值中的选定数字后立即停止一个键.
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);请注意,我尚未对此进行测试,因此代码可以进行优化,因此在投票之前,请仅将其作为所提出问题的概念.
更多推荐
寻找下一个斐波那契数
发布评论