斐波那契數列三種實現函式

馮建俊發表於2019-02-27

方法一:

let fn = (function fn(n){    
    let _catch = {};    
    function f(n){            
        if(n == 1 || n == 2){            
            return 1;        
        }        
    if(_catch[n]){            
        return _catch[n]       
    }        
    let prev2 = f(n-2);        
    let prev1 = f(n-1);       
    _catch[n-1] = prev1;        
    _catch[n-2] = prev2;        
    return prev + next;    
    }    
    return f;
})()
console.log(fn(5))複製程式碼

方法二:

function fn1(n){    
    let [a,b] = [0,1]    
    for(let i = 1;i<n;i++){        
        [a,b] = [b,a+b]     
    }    
    return b
}
console.log(fn1(2))複製程式碼

方法三:

function fn2(n){   
    return Array(n-1).fill().reduce(([a,b],)=>{        
        return [b,a+b]    
    },[0,1])[1]
}
console.log(fn2(1))複製程式碼


相關文章