PYTHON MEBY

Pythonで最大公約数・最小公倍数を計算(math.gcd, lcm (Python 3.9以降))

この記事では、Pythonのmathモジュールにあるgcd()関数とlcm()関数を使用して、最大公約数(GCD)と最小公倍数(LCM)を計算する方法を説明します。Python 3.9以降で利用可能です。

目次

最大公約数 (GCD) の計算

最大公約数 (GCD) は、2つ以上の整数を割り切る最大の整数です。Python 3.9以降では、mathモジュールのgcd()関数が利用できます。

import math

a = 48
b = 18
gcd = math.gcd(a, b)
print(f'{a}{b} の最大公約数は {gcd} です')

gcd()関数は、2つ以上の整数の最大公約数を返します。引数は整数型である必要があります。

import math

a = 48
b = 18
c = 30
gcd = math.gcd(a, b, c)
print(f'{a}, {b}, {c} の最大公約数は {gcd} です') 

最小公倍数 (LCM) の計算

最小公倍数 (LCM) は、2つ以上の整数で割り切れる最小の正の整数です。Python 3.9以降では、mathモジュールのlcm()関数が利用できます。

import math

a = 48
b = 18
lcm = math.lcm(a, b)
print(f'{a}{b} の最小公倍数は {lcm} です')

lcm()関数は、2つ以上の整数の最小公倍数を返します。引数は整数型である必要があります。

import math

a = 48
b = 18
c = 30
lcm = math.lcm(a, b, c)
print(f'{a}, {b}, {c} の最小公倍数は {lcm} です') 

いくつかの例を見てみましょう。

import math

# 例1
print(f'math.gcd(12, 18): {math.gcd(12, 18)}')
print(f'math.lcm(12, 18): {math.lcm(12, 18)}')

# 例2
print(f'math.gcd(15, 25, 35): {math.gcd(15, 25, 35)}')
print(f'math.lcm(15, 25, 35): {math.lcm(15, 25, 35)}')

# 例3: 0を含む場合
print(f'math.gcd(0, 10): {math.gcd(0, 10)}') # 0を含む場合は、GCDは0以外の数の絶対値となる
print(f'math.lcm(0, 10): {math.lcm(0, 10)}') # 0を含む場合は、LCMは0となる

関連記事