|
5 | 5 | """
|
6 | 6 |
|
7 | 7 |
|
8 |
| -def gcd(a, b): |
9 |
| - """Calculate Greatest Common Divisor (GCD).""" |
10 |
| - return b if a == 0 else gcd(b % a, a) |
| 8 | +def greatest_common_divisor(a, b): |
| 9 | + """ |
| 10 | + Calculate Greatest Common Divisor (GCD). |
| 11 | + >>> greatest_common_divisor(24, 40) |
| 12 | + 8 |
| 13 | + """ |
| 14 | + return b if a == 0 else greatest_common_divisor(b % a, a) |
| 15 | + |
| 16 | + |
| 17 | +""" |
| 18 | +Below method is more memory efficient because it does not use the stack (chunk of memory). |
| 19 | +While above method is good, uses more memory for huge numbers because of the recursive calls |
| 20 | +required to calculate the greatest common divisor. |
| 21 | +""" |
| 22 | + |
| 23 | + |
| 24 | +def gcd_by_iterative(x, y): |
| 25 | + """ |
| 26 | + >>> gcd_by_iterative(24, 40) |
| 27 | + 8 |
| 28 | + >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) |
| 29 | + True |
| 30 | + """ |
| 31 | + while y: # --> when y=0 then loop will terminate and return x as final GCD. |
| 32 | + x, y = y, x % y |
| 33 | + return x |
11 | 34 |
|
12 | 35 |
|
13 | 36 | def main():
|
14 |
| - """Call GCD Function.""" |
| 37 | + """Call Greatest Common Divisor function.""" |
15 | 38 | try:
|
16 |
| - nums = input("Enter two Integers separated by comma (,): ").split(",") |
| 39 | + nums = input("Enter two integers separated by comma (,): ").split(",") |
17 | 40 | num_1 = int(nums[0])
|
18 | 41 | num_2 = int(nums[1])
|
19 |
| - print(f"gcd({num_1}, {num_2}) = {gcd(num_1, num_2)}") |
| 42 | + print(f"greatest_common_divisor({num_1}, {num_2}) = {greatest_common_divisor(num_1, num_2)}") |
| 43 | + print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") |
20 | 44 | except (IndexError, UnboundLocalError, ValueError):
|
21 |
| - print("Wrong Input") |
| 45 | + print("Wrong input") |
22 | 46 |
|
23 | 47 |
|
24 | 48 | if __name__ == "__main__":
|
|
0 commit comments