迭代算法
fib-arr1.js
//
start = new Date();
function fib(n) {
var x = 0;
var y = 1;
var z = 0;
if(n == 0){
return x;
} else if (n == 1) {
return y;
}
else{
for (let i = 0; i <= n-2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
}
//
p = 40;
var arrf = [];
for (let i = 0; i < p; i++) {
m = fib(i);
arrf.push(m);
};
console.log(arrf);
//
end = new Date();
time = end.getTime() - start.getTime();
console.log("The cost time is :" + time + "ms");
运行结果:
[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, ... 39088169, 63245986 ]
The cost time is :65ms
迭代算法会重复的循环运算,并将运算结果通过赋值的形式,追加到新的运算中来求出新的结果。
递归算法
fib-arr2.js
//
start = new Date();
function fib(n){
if(n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
//
p = 40;
var arrf = [];
for (let i = 0; i < p; i++) {
m = fib(i);
arrf.push(m);
};
console.log(arrf);
//
end = new Date();
time = end.getTime() - start.getTime();
console.log("The cost time is :" + time + "ms");
运行结果:
[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 87, 1597, ... 39088169,
63245986 ]
The cost time is :7368ms
递归算法会循环的引用,将每次计算的过程引入下一次计算中,最后一次运算出结果。
运行环境是Windows上的node.js,Linux上会更快些。
网友评论