寻找下一个斐波那契数

编程入门 行业动态 更新时间:2024-10-23 03:20:02
本文介绍了寻找下一个斐波那契数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要找到一个给出整数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);

请注意,我尚未对此进行测试,因此代码可以进行优化,因此在投票之前,请仅将其作为所提出问题的概念.

更多推荐

寻找下一个斐波那契数

本文发布于:2023-11-30 04:11:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648675.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!