斐波那契数列

斐波那契数列

fib.png

Text Only
1
2
3
4
5
6
n=2: 1+0 = 1
n=3: 1+1 = 2
n=4: 2+1 = 3
n=5: 3+2 = 5
n=6: 5+3 = 8
n=7: 8+5 = 13

Python 实现

Python
def fib(n):
    a,b=0,1
    while n>0:
        c=a+b
        a=b
        b=c
        # a,b=b,a+b
        print(a)
        n=n-1

fib(10)

JavaScript 的两种实现

JavaScript
// 递归
function fibRecursion(n=10) {
    var _fn = (a,b,n)=>{
        if (n == 0) {
            return a
        }
        console.log(a)
        return _fn(b, a + b, n - 1)
    }
    return _fn(0, 1, n)
}
fibRecursion()

// 循环
function fibLoop(n=10) {
    var a = 0
      , b = 1

    while (n > 0) {
        console.log(a)
        var c = a + b // 需要缓存两个数相加的值
        a = b
        b = c
        n--
    }
    return a
}
fibLoop()