裴波那契數列(javascript實現)

東東dd發表於2018-09-16

遞迴方式實現

function fibonacci (num) {
    if (num === 1 || num === 2) {
        return 1;
    }
    return fibonacci(num - 1) + fibonacci(num - 2);
}
複製程式碼

非遞迴方式實現

function fibonacci (num) {
    var n1 = 1,
        n2 = 1,
        n = 1;
    for (var i = 3; i <= num; i++) {
        n = n1 + n2;
        n1 = n2;
        n2 = n;
    }
    return n ;
}
複製程式碼

相關文章