PHP斐波那契数列 [英] PHP Fibonacci Sequence

查看:113
本文介绍了PHP斐波那契数列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个php方法假设使用for循环将斐波那契数列打印到指定的值。

 <?php 
function fib($ n){//我不确定为什么它不起作用? ($ n <0; $ n <30; $ n ++){
if($ n <3){return $ n;
)的变量n(序列号) } //如果n小于3则返回n(1或2)
else {return fib($ n - 1)+ fib($ n - 2); }
/ *如果数字为3或以上,则执行2个和(n-1)和(n-2)
,然后将这2个和相加(n-1)+(n-2)
示例斐波纳契数字4
(4-1)+(4-2)= 5
3 + 2 = 5
* /
}
print $ N;
?>


解决方案

实际上有一种计算斐波纳契数的方法,通过使用四舍五入:

http:
$ b $ pre $函数getFib($ n)

return round(pow((sqrt(5)+1)/ 2,$ n)/ sqrt(5));
}


This php method is suppose to print the Fibonacci sequence up to a specified value using a for loop. I am unsure why it does not work?

<?php
function fib ($n) { // a function called fib, declaire variable n (the sequence number)
    for ($n=0;$n<30;$n++) {
        if ($n < 3) { return $n; } // if n is smaller than 3 return n (1 or 2)
        else { return fib ($n - 1) + fib ($n - 2); } 
    /* if the number is 3 or above do 2 sums (n-1) and (n-2)
    and then add the 2 sums together (n-1)+(n-2)
    Example Fibonacci number 4
    (4-1)+(4-2) = 5
    3 + 2 = 5
    */
}
print $n;
?>

There is actually a way to calculate a Fibonacci number without iteration by using rounding:

http://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding

function getFib($n)
{
    return round(pow((sqrt(5)+1)/2, $n) / sqrt(5));
}

这篇关于PHP斐波那契数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆