Skip to content

Commit db6e325

Browse files
thekaleidoscopesangamcse
authored andcommitted
extended_euclidean_gcd.py: Add Extended Euclidean
This adds Extended Euclidean Algorithm with Python implementation of the same. This implementation uses the iterative method of the algorithm, takes two values and gives out the gcd along with the polynomial equation to get inverse directly if the gcd is 1. The code uses generic notations and naming standard used in documentation along with that found in Wikipedia. Closes #3
1 parent 21265c7 commit db6e325

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Element style: gcd(a,b)-> a*x + b*y = r = gcd(a,b)
2+
3+
# Inverse of elements if gcd(a,b)==1:
4+
# * a^-1 mod (b) = x mod(b)
5+
# * b^-1 mod (a) = y mod(a)
6+
7+
# Naming is according to Bézout's identity, matching to that on Wikipedia
8+
9+
10+
def extended_euclidean_gcd(a, b):
11+
x, y, u, v = 0, 1, 1, 0
12+
while a != 0:
13+
q, r = b//a, b % a
14+
m, n = x-u*q, y-v*q
15+
b, a, x, y, u, v = a, r, u, v, m, n
16+
17+
gcd = b
18+
return gcd, x, y
19+
20+
21+
def main():
22+
a, b = 26, 15
23+
gcd, x, y = extended_euclidean_gcd(a, b)
24+
print("GCD of {} and {} is {}".format(a, b, gcd))
25+
print("The Equation : {}*{} + {}*{} = {}".format(a, x, b, y, gcd))
26+
27+
28+
if __name__ == '__main__':
29+
main()

0 commit comments

Comments
 (0)