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となる
関連記事
- Pythonで四捨五入・切り上げ・切り捨て(round, math.ceil, math.floor)
- Pythonで三角関数を計算(math.sin, math.cos, math.tan, etc.)
- Pythonで対数・指数関数を計算(math.log, math.exp, etc.)
- Pythonで絶対値を取得(abs)
- Pythonで分数演算(fractions.Fraction)
- Pythonで十進数演算(decimal.Decimal)
- Pythonで整数・浮動小数点数・複素数間の型変換
- Pythonでべき乗計算(**)
- Pythonで数値の書式設定(format, f文字列 (Python 3.6以降))
- Pythonでラムダ式(無名関数)を使う(lambda)