Skip to content

Commit 33300dd

Browse files
committed
Merge pull request nryoung#29 from utsavgupta/master
Added Extended Greatest Common Divisor Algorithm
2 parents d1a33bc + 01b7481 commit 33300dd

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

algorithms/math/__init__.py

Whitespace-only changes.

algorithms/math/extended_gcd.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
13+
def extended_gcd(p, q):
14+
15+
(a, b) = (p, q)
16+
17+
if a < 0:
18+
a = -1 * a
19+
20+
if b < 0:
21+
b = -1 * b
22+
23+
x0 = 0
24+
y1 = 0
25+
26+
x1 = 1
27+
y0 = 1
28+
29+
while(b != 0):
30+
quotient = a / b
31+
(a, b) = (b, a % b)
32+
(x1, x0) = (x0 - quotient * x1, x1)
33+
(y1, y0) = (y0 - quotient * y1, y1)
34+
35+
if p < 0:
36+
y0 = -1 * y0
37+
38+
if q < 0:
39+
x0 = -1 * x0
40+
41+
return (y0, x0)

algorithms/tests/test_math.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import unittest
2+
from ..math.extended_gcd import extended_gcd
3+
4+
5+
class TestExtendedGCD(unittest.TestCase):
6+
7+
def test_extended_gcd(self):
8+
# Find extended_gcd of 35 and 77
9+
(a, b) = extended_gcd(35, 77)
10+
self.assertIs(35 * a + 77 * b, 7)
11+
12+
# Find extended_gcd of 15 and 19
13+
(a, b) = extended_gcd(15, 19)
14+
self.assertIs(15 * a + 19 * b, 1)
15+
16+
# Find extended_gcd of 18 and 9
17+
(a, b) = extended_gcd(18, 9)
18+
self.assertIs(18 * a + 9 * b, 9)
19+
20+
# Find extended_gcd of 99 and 81
21+
(a, b) = extended_gcd(99, 81)
22+
self.assertIs(99 * a + 81 * b, 9)
23+
24+
# Find extended_gcd of 50 and 15
25+
(a, b) = extended_gcd(50, 15)
26+
self.assertIs(50 * a + 15 * b, 5)

0 commit comments

Comments
 (0)