LoginSignup
3
3

More than 3 years have passed since last update.

Python3.4で最大公約数(GCD)と最小公倍数(LCM)

Last updated at Posted at 2019-08-26

なぜPython3.4

AtCoderの現在のPythonのバージョンが3.4だから。
また、使用するモジュールが最新の3.7と異なるため。

最大公約数(GCD)

>>> from fractions import gcd
>>> gcd(4,6)
2
>>> gcd(8,12)
4

ちなみに、Python3.7では、mathモジュールに移行されている。

最小公倍数(LCM)

GCDを使って求められる。

>>> from fractions import gcd
>>> x, y = 2, 4; (x * y) // gcd(x, y)
4
>>> x, y = 8, 12; (x * y) // gcd(x, y)
24

リストのLCMを求める

def lcm(a):
    from fractions import gcd
    x = a[0]
    for i in range(1, len(a)):
        x = (x * a[i]) // gcd(x, a[i])
    return x

a = [3,4,6]
print(lcm(a))  # 実行結果: 12
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3