2
3

ユークリッドの互除法を使った最大公約数を求めるプログラムを実装しました

Posted at

ユークリッドの互除法を使って最大公約数を求めるPythonプログラムを実装しました。

###########################
## ユークリッドの互除法
##########################

input_line1 = input("MとNを、M Nの形式で入力してください\n")
array1 = input_line1.split(' ')
M = int(array1[0])
N = int(array1[1])
if M < N:
  tmp = N
  N = M
  M = tmp

while True:
  d = M % N
  if d == 0:
    print(N)
    break
  M = N
  N = d

試しに、M = 40 N = 16で実行します。

uuu.jpg

実際に計算すると

40 % 16 = 8
16 / 8 = 0
最大公約数は8ですね

2
3
2

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
2
3