File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments