2
2
Greatest Common Divisor.
3
3
4
4
Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor
5
+
6
+ gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility
5
7
"""
6
8
7
9
8
- def greatest_common_divisor (a , b ) :
10
+ def greatest_common_divisor (a : int , b : int ) -> int :
9
11
"""
10
12
Calculate Greatest Common Divisor (GCD).
11
13
>>> greatest_common_divisor(24, 40)
@@ -20,31 +22,44 @@ def greatest_common_divisor(a, b):
20
22
1
21
23
>>> greatest_common_divisor(16, 4)
22
24
4
25
+ >>> greatest_common_divisor(-3, 9)
26
+ 3
27
+ >>> greatest_common_divisor(9, -3)
28
+ 3
29
+ >>> greatest_common_divisor(3, -9)
30
+ 3
31
+ >>> greatest_common_divisor(-3, -9)
32
+ 3
23
33
"""
24
- return b if a == 0 else greatest_common_divisor (b % a , a )
25
-
26
-
27
- """
28
- Below method is more memory efficient because it does not use the stack (chunk of
29
- memory). While above method is good, uses more memory for huge numbers because of the
30
- recursive calls required to calculate the greatest common divisor.
31
- """
34
+ return abs (b ) if a == 0 else greatest_common_divisor (b % a , a )
32
35
33
36
34
- def gcd_by_iterative (x , y ) :
37
+ def gcd_by_iterative (x : int , y : int ) -> int :
35
38
"""
39
+ Below method is more memory efficient because it does not create additional
40
+ stack frames for recursive functions calls (as done in the above method).
36
41
>>> gcd_by_iterative(24, 40)
37
42
8
38
43
>>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40)
39
44
True
45
+ >>> gcd_by_iterative(-3, -9)
46
+ 3
47
+ >>> gcd_by_iterative(3, -9)
48
+ 3
49
+ >>> gcd_by_iterative(1, -800)
50
+ 1
51
+ >>> gcd_by_iterative(11, 37)
52
+ 1
40
53
"""
41
54
while y : # --> when y=0 then loop will terminate and return x as final GCD.
42
55
x , y = y , x % y
43
- return x
56
+ return abs ( x )
44
57
45
58
46
59
def main ():
47
- """Call Greatest Common Divisor function."""
60
+ """
61
+ Call Greatest Common Divisor function.
62
+ """
48
63
try :
49
64
nums = input ("Enter two integers separated by comma (,): " ).split ("," )
50
65
num_1 = int (nums [0 ])
0 commit comments