简体   繁体   English

按索引获取斐波那契数 - PHP

[英]Get Fibonacci number By Index - PHP

I have a simple PHP function that returns Fibonacci numbers by index and it works:我有一个简单的 PHP function 按索引返回斐波那契数,它可以工作:

function fibIndexCalculator($index)
{
    $numbers = [0, 1];
    for ($i = 0; $i < $index; $i++) {
        $lastNumbers = array_slice($numbers, count($numbers) - 2, 2);
        $numbers[] = $lastNumbers[0] + $lastNumbers[1];
    }
    return end($numbers);
}
var_dump(fibIndexCalculator(4));

But if I give the function an index like 200000, then only after 1 hour I can see the result.但是如果我给 function 一个像 200000 这样的索引,那么只有在 1 小时后我才能看到结果。

Is there any way to change the algorithm for getting the Fibonacci number with a large index in a fast way?有什么方法可以改变算法以快速获取具有大索引的斐波那契数?

if I give the function an index like 200000, then only after 1 hour I can see the result.如果我给 function 一个像 200000 这样的索引,那么只有在 1 小时后我才能看到结果。

If you do that you'll not see any useful result.如果你这样做,你将看不到任何有用的结果。 The output will be INF. output 将是 INF。 This is because The 64-bit floating point that PHP uses has a maximum value it can represent that is somewhere near 1.797E+308.这是因为 PHP 使用的 64 位浮点具有它可以表示的最大值,即接近 1.797E+308。 The Fibonacci number with index 1475 is already around 1E+308...索引为 1475 的斐波那契数已经在 1E+308 左右...

But up to the limit of floating point, you can use the following direct formula:但在浮点数的限制下,您可以使用以下直接公式:

function fibIndexCalculator($index) {
    $SQRT5 = sqrt(5);
    return round(((1 + $SQRT5) / 2)**$index / $SQRT5);
}

If you want to stick to the iterative solution, then note how you accumulate an array, where you never use the old values in that array again -- only the last two values.如果您想坚持迭代解决方案,请注意您如何累积一个数组,您再也不会使用该数组中的旧值 - 只有最后两个值。 So don't keep an array, but just two variables:所以不要保留一个数组,而只保留两个变量:

function fibIndexCalculator2($index) {
    if ($index < 2) return $index;
    $b = 1;
    $c = 1;
    while ($index > 2) {
        $a = $b;
        $b = $c;
        $c = $a + $b;
        $index--;
    }
    return $c;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM