C最大公因數程式

在Python中,可以使用math.gcd()函式來找出兩個或多個整數之間的最大公約數(Greatest Common Divisor, 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 greatest common divisor of", a, "and", b, "is", gcd)

如果你需要計算多個整數的最大公約數,你可以使用循環來對每個數套用math.gcd()函式。例如:

import math

numbers = [int(n) for n in input("Enter the numbers separated by spaces: ").split()]

def gcd_of_list(numbers):
    if len(numbers) == 1:
        return numbers[0]
    else:
        return gcd_of_list(numbers[1:], numbers[0])

def gcd_of_list(numbers, start):
    if len(numbers) == 1:
        return start
    else:
        return gcd_of_list(numbers[1:], math.gcd(start, numbers[0]))

gcd = gcd_of_list(numbers, numbers[0])
print("The greatest common divisor of", numbers, "is", gcd)

在這個例子中,我們定義了一個函式gcd_of_list,它接受一個整數列表作為參數,並返回這個列表的最大公約數。函式內部,我們使用了一個遞歸算法來找到最大公約數。首先,我們檢查列表的長度,如果列表中只有一個元素,那麼這個元素就是最大公約數。否則,我們遞歸地調用函式,將列表中除第一個元素之外的所有元素作為參數,並將第一個元素作為第二個參數。這樣,我們就可以找到剩餘元素的最大公約數,然後與第一個元素的最大公約數。最終,我們將得到整個列表的最大公約數。