Skip to content

Commit 7cae6ff

Browse files
committed
Handle gcd(0, 0) edge case
1 parent 68c846d commit 7cae6ff

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

maths/greatest_common_divisor.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,11 @@ def greatest_common_divisor(a: int, b: int) -> int:
3030
3
3131
>>> greatest_common_divisor(-3, -9)
3232
3
33+
>>> greatest_common_divisor(0, 0)
34+
0
3335
"""
36+
if a == 0 and b == 0:
37+
return 0
3438
return abs(b) if a == 0 else greatest_common_divisor(b % a, a)
3539

3640

@@ -50,8 +54,12 @@ def gcd_by_iterative(x: int, y: int) -> int:
5054
1
5155
>>> gcd_by_iterative(11, 37)
5256
1
57+
>>> gcd_by_iterative(0, 0)
58+
0
5359
"""
54-
while y: # --> when y=0 then loop will terminate and return x as final GCD.
60+
if x == 0 and y == 0:
61+
return 0
62+
while y:
5563
x, y = y, x % y
5664
return abs(x)
5765

0 commit comments

Comments
 (0)