用JavaScript(js) 实现斐波那契数列函数4种方法
斐波那契数列(Fibonacci sequence),又称黄金分割数列、因数学家莱昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……在数学上,斐波那契数列以如下被以递推的方法定义:F(0)=0,F(1)=1, F(n)=F(n – 1)+F(n – 2)(n ≥ 2,n ∈ N*)在现代物理、准晶体结构、化学等领域,斐波纳契数列都有直接的应用,为此,美国数学会从 1963 年起出版了以《斐波纳契数列季刊》为名的一份数学杂志,用于专门刊载这方面的研究成果。
知道概念后,如何用JavaScript函数斐波那契数列第N个数的值呢?
1、递归算法
function myFibonacci(n){
if(n < 0){
console.log('输入的数字不能小于0');
return;
}
if(n === 0){ return 0;}
if(n === 1){ return 1;}
if(n === 2){ return 1;}
if(n > 2) {
return myFibonacci(n-1)+myFibonacci(n-2)
} else {
return n;
}
}
console.log(myFibonacci(-1)); //undefined
console.log(myFibonacci(0)); //0
console.log(myFibonacci(1)); //1
console.log(myFibonacci(2)); //1
console.log(myFibonacci(3)); //2
console.log(myFibonacci(4)); //3
console.log(myFibonacci(5)); //5
console.log(myFibonacci(6)); //8
console.log(myFibonacci(7)); //13
console.log(myFibonacci(8)); //21
console.log(myFibonacci(9)); //34
优点:代码比较简洁易懂;
缺点:当数字太大时,会变得特别慢,每次都重复计算会造成不必要的浪费,所以这种方法并不是很好。
2、for循环方法
function myFibonacci(n){
if(n < 0){
console.log('输入的数字不能小于0');
return;
}
if(n === 0){ return 0;}
if(n === 1){ return 1;}
if(n === 2){ return 1;}
var first = 1,second = 1,third;
if(n>2){
for(var i = 0; i < n-2; i++){
third = first + second;
first = second;
second = third;
}
return third;
}else{
return n;
}
}
console.log(myFibonacci(-1)); //undefined
console.log(myFibonacci(0)); //0
console.log(myFibonacci(1)); //1
console.log(myFibonacci(2)); //1
console.log(myFibonacci(3)); //2
console.log(myFibonacci(4)); //3
console.log(myFibonacci(5)); //5
console.log(myFibonacci(6)); //8
console.log(myFibonacci(7)); //13
console.log(myFibonacci(8)); //21
console.log(myFibonacci(9)); //34
3、数组方法
function myFibonacci(n){
var arr = [0,1,1]
if(n<0){
console.log('输入的数字不能小于0')
return;
}
if(n>=3){
for(var i = 3; i <= n; i++){
arr[i] = arr[i-1]+arr[i-2]
}
}
return arr[n];
}
console.log(myFibonacci(-1)); //undefined
console.log(myFibonacci(0)); //0
console.log(myFibonacci(1)); //1
console.log(myFibonacci(2)); //1
console.log(myFibonacci(3)); //2
console.log(myFibonacci(4)); //3
console.log(myFibonacci(5)); //5
console.log(myFibonacci(6)); //8
console.log(myFibonacci(7)); //13
console.log(myFibonacci(8)); //21
console.log(myFibonacci(9)); //34
4、使用闭包方法
function myFibonacci(n){
if(n<0){
console.log('输入的数字不能小于0')
return;
}
let arr = [0,1];//在外部函数中定义数组,内部函数给数组添加值
function calc(n){
if(n<2){
return arr[n];
}
if(arr[n] != undefined){
return arr[n];
}
let data = calc(n-1) + calc(n-2);//使用data将每次递归得到的值保存起来
arr[n] = data;//将每次递归得到的值放到数组中保存
return data;
}
return calc(n);
}
console.log(myFibonacci(-1)); //undefined
console.log(myFibonacci(0)); //0
console.log(myFibonacci(1)); //1
console.log(myFibonacci(2)); //1
console.log(myFibonacci(3)); //2
console.log(myFibonacci(4)); //3
console.log(myFibonacci(5)); //5
console.log(myFibonacci(6)); //8
console.log(myFibonacci(7)); //13
console.log(myFibonacci(8)); //21
console.log(myFibonacci(9)); //34