-
Notifications
You must be signed in to change notification settings - Fork 497
/
euclidean_gcd.py
47 lines (39 loc) · 1.48 KB
/
euclidean_gcd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
There are two implementations:
Recursive (euclidean_gcd_recursive) and
Non-Recursive (euclidean_gcd)
"""
def euclidean_gcd_recursive(first, second):
"""
Calculates GCD of two numbers using Euclidean Recursive Algorithm
:param first: First number
:param second: Second number
:return: GCD of the numbers
"""
if second == 0:
return first # First becomes gcd if second becomes zero
else:
return euclidean_gcd(second, first % second)
def euclidean_gcd(first, second):
"""
Calculates GCD of two numbers using Euclidean Iterative Algorithm
:param first: First number
:param second: Second number
:return: GCD of the numbers
"""
while second != 0: # Iterate till second becomes zero
temp = second # Temporary variable to hold value of second
second = first % second
first = temp # Temporary variable assigned to first
return first # When second becomes 0, first becomes gcd of both
def main():
first = 36
second = 6
answer_iterative = euclidean_gcd(first, second)
answer_recursive = euclidean_gcd_recursive(first, second)
print("GCD of %d and %d is : %d by recursive algo." % (first, second,
answer_recursive))
print("GCD of %d and %d is : %d by iterative algo." % (first, second,
answer_iterative))
if __name__ == '__main__':
main()