2018年1月8日 星期一

Python: Compute the greatest common divisor (GCD) of two positive integers

Python: Compute the greatest common divisor (GCD) of two positive integers

Python Basic: Exercise-31 with Solution

Write a Python program to compute the greatest common divisor (GCD) of two positive integers.
Sample Solution:-
def gcd(x, y):
    gcd = 1
    
    if x % y == 0:
        return y
    
    for k in range(int(y / 2), 0, -1):
        if x % k == 0 and y % k == 0:
            gcd = k
            break  
    return gcd

print(gcd(12, 17))
print(gcd(10, 16))
print(gcd(8, 16))

========== RESTART: F:/Python_APSC/py-ex-basic-31.py ==========
1
2
8
>>> 


沒有留言:

張貼留言

8-QAM Signal 4 Phases 2 Amplitudes + 8PSK

 8-QAM Signal 4 Phases 2 Amplitudes + 8PSK import tkinter as tk from tkinter import messagebox import math import cmath # --- 8-QAM 參數設定 ---...