斐波那契数列实现的几种方式以及优略
2021-03-26 本文已影响0人
多年0以后
let arr = []
function fb(n) {
if(n < 1) {
return 0
} else if(n == 1 || n == 2) {
return 1
}
let first = 1
let second = 1
let next = first + second
for (let i = 3; i < n; i++) {
first = second
second = next
next = first + next
}
return next
}
function fb2(n) {
if(n < 1) {
return 0
} else if(n == 1 || n == 2) {
return 1
} else {
return fb2(n-2) + fb2(n-1)
}
}
let firstTimeStart = new Date().getTime()
for (let i=1; i<=40; i++) {
arr.push(fb(i))
}
console.log('the first way used time', new Date().getTime() - firstTimeStart)
let secondTimeStart = new Date().getTime()
for (let i=1; i<=40; i++) {
arr.push(fb2(i))
}
console.log( 'the second way used time', new Date().getTime() - secondTimeStart)