Python最公因數gcd和費氏數列fibonacci numbers

在Python中,你可以使用內置的math模塊來計算兩個數字的最小公因數(GCD),或者使用迴圈來計算費氏數列。

首先,安裝math模塊,如果你還沒有安裝的話:

pip install math

然後,你可以使用math.gcd函數來計算兩個數字的最小公因數:

import math

def gcd(a, b):
    return math.gcd(a, b)

# 使用示例
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print(f"The GCD of {a} and {b} is {gcd(a, b)}")

對於費氏數列,你可以使用迴圈來計算:

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

# 使用示例
n = int(input("Enter the number of terms: "))
print(f"The first {n} terms of the Fibonacci sequence are: {[fibonacci(i) for i in range(n)]}")

這裡,fibonacci函數使用了一個迴圈來計算費氏數列的前n項。range(n)用來控制迴圈執行n次,每次疊代將ab的值交換並相加,最後返回a的值。

請注意,費氏數列的定義是:費氏數列的每一項都是由前兩項的和所構成,起始項是0和1。所以,fibonacci(0)等於0,fibonacci(1)等於1,fibonacci(n)等於fibonacci(n-1)fibonacci(n-2)的和,其中n大於2。