通过下标求值
function fib(index){
let arr = [1,1]
for(let i = 2;i < index + 1;i++){
arr.push(arr[i - 1] + arr[i - 2])
}
return arr[index]
}
function fib(index){
let pre = 1,cur = 1,next;
if(index < 2){
return 1
}
for(let i = 2;i < index + 1;i++){
next = pre + cur
pre = cur;
cur = next;
}
return next
}
非尾递归
function fib(index) {
if (index <= 1){
return 1
};
return fib(index - 1) + fib(index - 2);
}
尾递归
function fib(index,pre = 1,cur = 1){
if(index <= 1){
return cur
}
return fib(index - 1,cur,pre + cur)
}
通过值求下标
function fib(val){
if(val == 1){
return 0
}
let pre = 1,cur = 1,next;
for(let i = 2;i < val;i++){
next = pre + cur
pre = cur;
cur = next;
if(val == next){
return i
}else if(next > val){
return -1
}
}
}
function fib(val){
if(val == 1){
return 0
}
let pre = 1,cur = 1,next = pre + cur,i = 2;
while(next <= val){
if(next == val){
return i
}
pre = cur;
cur = next;
next = pre + cur
i++
}
return -1
}