Fibonacci

million_yh發表於2024-03-28
# 1.Recursion slow
def fibonacci_recursion(n):
    if n <= 1:
        return n
    else:
        return fibonacci_recursion(n-1) + fibonacci_recursion(n-2)
# 2.List save every value, avoid repeate compute fast
def fibonacci_list(n):
    F =[0,1]
    if n<=1 :
        return n
    else:
        for i in range(2,n+1):
            F.append(F[i-1] + F[i-2])#soul
    return F[n]
# 3.1 for loop, update a and b,don't need List, increase space efficiency and reduce time complexity O(n)
def fibonacci_forloop_update(n):
    if n<=1 :
        return n
    else:
        a,b = 0,1
        for _ in range(2,n+1):
            a,b = b,a+b
        return b
# 3.2 while loop, update a and b,don't need List, increase space efficiency and reduce time complexity O(n)
def fibonacci_whileloop_update(n):
    if n<=1 :
        return n
    else:
        a,b = 0,1
        i = 2
        while i <= n:
            a,b = b,a+b
            i+=1
        return b
for i in range(100):
    # print(fibonacci_list(i))
    # print(fibonacci_recursion(i))
    # print(fibonacci_forloop_update(i))
    print(fibonacci_whileloop_update(i))

About Fibonacci formula: https://www.zhihu.com/question/25217301

相關文章