//斐波那契数列
function fibonacci(n) {
if (n === 0) {
return [];
} else if (n === 1) {
return [0];
} else if (n === 2) {
return [0, 1];
} else {
var sequence = [0, 1];
for (var i = 2; i < n; i++) {
var nextNumber = sequence[i - 1] + sequence[i - 2];
sequence.push(nextNumber);
}
return sequence;
}
}
// 示例输出
console.log(fibonacci(0)); // 输出: []
console.log(fibonacci(1)); // 输出: [0]
console.log(fibonacci(10)); // 输出: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
//循环实现
const fibonacciSequence = function (num){
if(num==1||num==2){
return 1
}
let prev = 0;
let next = 1;
let total = 1;
for(let i=1 ;i<num;i++){
if(i==1||i==2){
total=1
}
total = prev+next
prev = next
next = total
}
return total
}
fibonacciSequence(200)