Skip to content

Commit 7444a1f

Browse files
subahaniicclauss
authored andcommitted
Another method added for GCD (TheAlgorithms#1387)
* Another method added for GCD * Now doctest fulfilled for added method. * Update greatest_common_divisor.py * Now unnecessary white spaces removed. * Cycle_Detection_Undirected_Graph Cycle_Detection_Undirected_Graph using Disjoint set DataStructure * Update greatest_common_divisor.py again * Again Updated cycle_detection_undirected_graph.py * Delete cycle_detection_undirected_graph.py * Add doctests and format the code with psf/black * fixup: Typo * Update greatest_common_divisor.py * greatest_common_divisor()
1 parent 13802fc commit 7444a1f

File tree

1 file changed

+31
-7
lines changed

1 file changed

+31
-7
lines changed

maths/greatest_common_divisor.py

+31-7
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,44 @@
55
"""
66

77

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
1134

1235

1336
def main():
14-
"""Call GCD Function."""
37+
"""Call Greatest Common Divisor function."""
1538
try:
16-
nums = input("Enter two Integers separated by comma (,): ").split(",")
39+
nums = input("Enter two integers separated by comma (,): ").split(",")
1740
num_1 = int(nums[0])
1841
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)}")
2044
except (IndexError, UnboundLocalError, ValueError):
21-
print("Wrong Input")
45+
print("Wrong input")
2246

2347

2448
if __name__ == "__main__":

0 commit comments

Comments
 (0)