Python – In ra dãy Fibonanci

Yêu cầu:
Viết chương trình in dãy số Fibonanci gồm N số.
Biết rằng:
f(0) = f(1) = 1
f(n) = f(n – 1) + f(n – 2)

Thuật toán:
– Cách 1: dùng đệ quy
– Cách 2: dùng công thức f(n) = f(n – 1) + f(n – 2)

Cách 1: dùng đệ quy
test.py

"""
# Author: VNCODING
# Function: Fibonanci
# 2022/08/17        first create    VNCODING
"""
def fibo(n):
    if n == 1:
        return 0
    if n == 2 or n == 3:
        return 1
    else:
        return fibo(n-1) + fibo(n-2)

print("Input the number of fibonanci: ")
N = input();
while int(N) < 1:
    print("Input the number of fibonanci again: ")
    N = input();

res = ""
for i in range(1, int(N)+1):
    res = res + str(fibo(i)) + ","

print(res)

Kết quả:
Input the number of fibonanci:
-1
Input the number of fibonanci again:
0
Input the number of fibonanci again:
5
1,1,2,3,5,

Cách 2: dùng công thức f(n) = f(n – 1) + f(n – 2)
test.py

#############################################################
# Author: VNCODING
# History
# 2022/08/17        first create    VNCODING
#############################################################
print("Input the number of fibonanci: ")
N = input();

while int(N) < 1:
    print("Input the number of fibonanci again: ")
    N = input();

Fn1 = 0
Fn2 = 1
Fn  = 0
fibo = ""
for i in range(0, int(N)):
    if i == 0:
        fibo = str(Fn1) + ", "
    elif i == 1:
        fibo = fibo + str(Fn2) + ", "
    else:
        Fn = Fn1 + Fn2
        fibo = fibo + str(Fn) + ", "
        Fn1 = Fn2
        Fn2 = Fn


print(fibo)

Kết quả:
Input the number of fibonanci:
-2
Input the number of fibonanci again:
7
0, 1, 1, 2, 3, 5, 8,

Be the first to comment

Leave a Reply