PHP斐波纳契数列

Jes*_*nge 8 php for-loop

这个php方法假设使用for循环将Fibonacci序列打印到指定值.我不确定为什么它不起作用?

<?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;
?>
Run Code Online (Sandbox Code Playgroud)

Lee*_*vis 37

实际上有一种方法可以通过使用舍入来计算斐波纳契数而无需迭代:

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

function getFib($n)
{
    return round(pow((sqrt(5)+1)/2, $n) / sqrt(5));
}
Run Code Online (Sandbox Code Playgroud)

  • 从PHP 5.6开始,你可以使用[exponentiation operator(`**`)](https://secure.php.net/manual/en/language.operators.arithmetic.php):`round(((***.5 + 1)/ 2)**$ n/5**.5)`. (5认同)
  • 让我对上面的解决方案进行一些优化:而不是使用整个表达式:“((5 ** .5 + 1) / 2)”,它实际上是一个黄金比例 - 使用“1.618”就足够了,而不是使用`5 ** .5` 只是 `2.236` 常数,因此我们有 `round(1.618 ** $n / 2.236)`。另一个注意事项 - 使用 round,您可以计算大约前 70 个连续数字,&gt;70(取决于 32/64 arch)该数字将用科学计数法转换为双精度,但您可以使用 `number_format/sprintf` (2认同)

小智 7

斐波纳契的简单功能

function fibonacci($n,$first = 0,$second = 1)
{
    $fib = [$first,$second];
    for($i=1;$i<$n;$i++)
    {
        $fib[] = $fib[$i]+$fib[$i-1];
    }
    return $fib;
}
echo "<pre>";
print_r(fibonacci(50));
Run Code Online (Sandbox Code Playgroud)


小智 6

在这个例子中,我使用for循环并将长度限制为10:

$x = 0;    
$y = 1; 

for($i=0;$i<=10;$i++)    
{    
    $z = $x + $y;    
    echo $z."<br />";         
    $x=$y;       
    $y=$z;     
}   
Run Code Online (Sandbox Code Playgroud)

输出:
1
2
3
5
8
13
21
34
55
89
144

  • 你应该在 for 循环之前 echo $x 和 $y ie `0 1`。 (2认同)