最小公倍數程式碼
以下是一個簡單的Python程式碼範例,用來計算兩個數字的最低公倍數(Greatest Common Divisor, GCD):
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
# 使用例子
a = int(input("First number: "))
b = int(input("Second number: "))
gcd_value = gcd(a, b)
print("The GCD of", a, "and", b, "is", gcd_value)
這個程式碼使用了遞歸的方法來計算GCD。遞歸的邏輯是,如果第二個數字(b)為0,那麼第一個數字(a)就是它們的GCD;否則,繼續計算a % b的GCD,直到b為0為止。
輸入兩個數字,程式會輸出它們的GCD。如果你想要計算最低公倍數(Least Common Multiple, LCM),你可以使用以下公式來計算:
def lcm(a, b):
return (a * b) // gcd(a, b)
這個公式是基於兩個數字的乘積除以它們的GCD來計算LCM。將這個函數加入到上面的程式碼中,你就可以同時輸出GCD和LCM:
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def lcm(a, b):
return (a * b) // gcd(a, b)
# 使用例子
a = int(input("First number: "))
b = int(input("Second number: "))
gcd_value = gcd(a, b)
lcm_value = lcm(a, b)
print("The GCD of", a, "and", b, "is", gcd_value)
print("The LCM of", a, "and", b, "is", lcm_value)
輸入兩個數字,程式會同時輸出它們的GCD和LCM。