斐波那契数列
已知: 斐波那契数列第n项是除前两项以外,第n-2与第n-1项的和:S(n) = S(n-2) + S(n-1)。
优化前
// 优化前
const n = "";
function getFibonacciSequenceItem(n) {
let arr = [0, 1];
let item = 0;
for (let i = 2; i < n; i++) {
item = arr[i - 2] + arr[i - 1];
arr.push(item);
}
return item;
}
console.log(getFibonacciSequenceItem(10));
优化后
// 优化后
const n = "";
function getFibonacciSequenceItem(n) {
let arr = [0, 1];
let item = 0;
if (n < 3) {
return arr[n];
}
for (let i = 2; i < n + 1; i++) {
item = arr[0] + arr[1];
arr[0] = arr[1];
arr[1] = item;
}
return item;
}
getFibonacciSequenceItem(10);
标签:arr,斐波,item,getFibonacciSequenceItem,let,项值,那契
From: https://www.cnblogs.com/Kidrue/p/16881139.html