P粉0989790482023-08-17 16:52:41
There is a closed formula for calculating the nth Fibonacci number, called the Binet formula. This allows you to get the nth number in asymptotic time complexity of O(1)
.
Here is an example showing how to calculate the Fibonacci number for any n
.
Extend this to solve your specific problem. I suggest calculating the values of n-1
and n
. Then iterate k times to get the desired value. Keep track of the results as you iterate and you should be fine.
function fibonacci(n) { const phi = (1 + Math.sqrt(5)) / 2; const psi = (1 - Math.sqrt(5)) / 2; // phi的负倒数 return Math.round((Math.pow(phi, n) - Math.pow(psi, n)) / Math.sqrt(5)); } // 测试 console.log(fibonacci(10)); // 输出:55
Note: Although this formula gives accurate results for smaller n
values, precision may be lost for larger values due to limitations of floating point operations in JavaScript .