Skip to content

Commit 563a46d

Browse files
committed
faster iterative gcd to avoid max recursion error
1 parent f435d43 commit 563a46d

File tree

1 file changed

+6
-9
lines changed

1 file changed

+6
-9
lines changed

math/gcd.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
'''
2-
Computes gcd of integers x,y using Euclid's Algorithm
2+
Computes gcd of integers a and b using Euclid's Algorithm
33
'''
44

55

6-
def gcd(x,y):
7-
x = abs(x) #gcd(a,b) = gcd(|a|,b) = gcd(a,|b|) = gcd(|a|,|b|)
8-
y = abs(y)
9-
if x>y: # To ensure x<=y
10-
x,y = y,x
11-
if x==0:
12-
return y
13-
return gcd(y % x, x) # Euclid's algorithm
6+
def gcd(a, b):
7+
while True:
8+
if b == 0:
9+
return a
10+
a, b = b, a % b

0 commit comments

Comments
 (0)