Python最公因數gcd if else

在Python中,可以使用math.gcd()函式來找到兩個或更多整數的最大公約數(Greatest Common Divisor,GCD)。這個函式返回的是兩個數字的GCD。

下面是一個簡單的例子,展示了如何使用math.gcd()函式來找到兩個整數的最大公約數:

import math

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

gcd = math.gcd(a, b)

print("The GCD of", a, "and", b, "is", gcd)

在這個例子中,我們首先導入了math模組,然後使用input()函式讓用戶輸入兩個整數,並將其轉換為整數類型。最後,我們使用math.gcd()函式來找到這兩個數的最大公約數,並列印出來。

如果你需要根據GCD的值來執行不同的操作,你可以使用if-else語句。下面是一個例子:

import math

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

gcd = math.gcd(a, b)

if gcd == 1:
    print("The numbers", a, "and", b, "are coprime.")
elif gcd == a or gcd == b:
    print("One of the numbers is a multiple of the other.")
else:
    print("The GCD of", a, "and", b, "is", gcd)

在這個例子中,我們首先計算了兩個數的GCD,然後根據GCD的值執行不同的操作。如果GCD等於1,這意味著兩個數互質;如果GCD等於a或b,這意味著其中一個數是另一個數的倍數;否則,我們列印出GCD的值。