Skip to content

Commit 2370a3c

Browse files
committed
Implement GCD program
1 parent c2e6d85 commit 2370a3c

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

algorithms/exercises/gcd.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
2+
def gcd(m, n):
3+
"""
4+
Euclid’s algorithm is based on repeated application of equality:
5+
6+
gcd(m,n) = gcd(n, m mod n)
7+
8+
until the second number becomes 0, which makes the problem trivial.
9+
10+
Time Complexity: O(min(m, n))
11+
"""
12+
13+
if n == 0:
14+
return m
15+
16+
return gcd(n, m % n)
17+
18+
def gcd_iterative(m, n):
19+
"""
20+
Computes the GCD of two positive integers iteratively.
21+
22+
Time Complexity: O(min(m, n))
23+
"""
24+
25+
while n > 0:
26+
remainder = m % n
27+
m = n
28+
n = remainder
29+
30+
return m
31+
32+
if __name__ == '__main__':
33+
34+
# Get the GCD (Greatest Common Divisor) with the recursive algorithm.
35+
result1 = gcd(60, 24)
36+
37+
# Get the GCD with the iterative algorithm.
38+
result2 = gcd_iterative(60, 24)
39+
40+
assert result1 == result2, "GCD is not same..."
41+
42+
print('GCD of 60 and 24:', result1)
43+
print('GCD of 60 and 24:', result2)
44+
45+
# Result:
46+
# ---
47+
#
48+
# GCD of 60 and 24: 12
49+
# GCD of 60 and 24: 12
50+

0 commit comments

Comments
 (0)