最大公因數c程式

最大公因數(Greatest Common Divisor, GCD),也稱為最大公約數,是指兩個或更多整數的共有最大因子。在程式設計中,可以使用多種方法來計算最大公因數,包括質因數分解、歐幾里得算法(Euclidean algorithm)和更快的庫函數。

以下是一個簡單的Python程式,使用歐幾里得算法來計算兩個數字的最大公因數:

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

# 使用例子
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print("The greatest common divisor of", a, "and", b, "is", gcd(a, b))

這個程式首先定義了一個名為 gcd 的函數,它使用歐幾里得算法來計算兩個數字的最大公因數。在 gcd 函數中,我們使用了一個迴圈來不斷地將 a 除以 b,直到 b 為零。此時,a 就是 ab 的最大公因數。

gcd 函數之外,我們提供了一個使用例子,它要求用戶輸入兩個數字,並使用 gcd 函數來計算它們的最大公因數。

如果你使用的Python版本較新,你也可以使用內置的 math.gcd 函數來計算最大公因數,這比自己實現的 gcd 函數要快得多:

import math

# 使用例子
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print("The greatest common divisor of", a, "and", b, "is", math.gcd(a, b))

在這個例子中,我們導入了 math 模組,並使用了 math.gcd 函數來計算最大公因數。