Skip to content

Commit 5d2be00

Browse files
committed
added extended gcd algorithm
1 parent 28fdf60 commit 5d2be00

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

algorithms/math/extended_gcd.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
extended_gcd.py
3+
4+
This module implements the extended greatest common divider algorithm.
5+
6+
Pre: two integers a and b
7+
Post: a tuple (x, y) where a*x + b*y = gcd(a, b)
8+
9+
Pseudo Code: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
10+
"""
11+
12+
def extended_gcd(p, q):
13+
14+
(a, b) = (p, q)
15+
16+
if a < 0: a = -1 * a
17+
if b < 0: b = -1 * b
18+
19+
x0 = y1 = 0
20+
x1 = y0 = 1
21+
22+
while(b!=0):
23+
quotient = a / b
24+
(a,b) = (b, a % b)
25+
(x1 , x0) = (x0 - quotient * x1, x1)
26+
(y1 , y0) = (y0 - quotient * y1, y1)
27+
28+
if p < 0: y0 = -1 * y0
29+
if q < 0: x0 = -1 * x0
30+
31+
return (y0, x0)

0 commit comments

Comments
 (0)