TheAlgorithms-Python
77 строк · 2.0 Кб
1"""
2Greatest Common Divisor.
3
4Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor
5
6gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility
7"""
8
9
10def greatest_common_divisor(a: int, b: int) -> int:11"""12Calculate Greatest Common Divisor (GCD).
13>>> greatest_common_divisor(24, 40)
148
15>>> greatest_common_divisor(1, 1)
161
17>>> greatest_common_divisor(1, 800)
181
19>>> greatest_common_divisor(11, 37)
201
21>>> greatest_common_divisor(3, 5)
221
23>>> greatest_common_divisor(16, 4)
244
25>>> greatest_common_divisor(-3, 9)
263
27>>> greatest_common_divisor(9, -3)
283
29>>> greatest_common_divisor(3, -9)
303
31>>> greatest_common_divisor(-3, -9)
323
33"""
34return abs(b) if a == 0 else greatest_common_divisor(b % a, a)35
36
37def gcd_by_iterative(x: int, y: int) -> int:38"""39Below method is more memory efficient because it does not create additional
40stack frames for recursive functions calls (as done in the above method).
41>>> gcd_by_iterative(24, 40)
428
43>>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40)
44True
45>>> gcd_by_iterative(-3, -9)
463
47>>> gcd_by_iterative(3, -9)
483
49>>> gcd_by_iterative(1, -800)
501
51>>> gcd_by_iterative(11, 37)
521
53"""
54while y: # --> when y=0 then loop will terminate and return x as final GCD.55x, y = y, x % y56return abs(x)57
58
59def main():60"""61Call Greatest Common Divisor function.
62"""
63try:64nums = input("Enter two integers separated by comma (,): ").split(",")65num_1 = int(nums[0])66num_2 = int(nums[1])67print(68f"greatest_common_divisor({num_1}, {num_2}) = "69f"{greatest_common_divisor(num_1, num_2)}"70)71print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}")72except (IndexError, UnboundLocalError, ValueError):73print("Wrong input")74
75
76if __name__ == "__main__":77main()78