forked from NITSkmOS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
extended_euclidean_gcd.py: Add Extended Euclidean GCD Algorithm
This adds Extended Euclidean Algorithm with Python implementation of the same. This implementation uses 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. Code uses generic notations and naming standard used in documentation along with that found in Wikipedia. Closes NITSkmOS#3 NITSkmOS#159
- Loading branch information
1 parent
43c82c4
commit 7bec1c1
Showing
2 changed files
with
56 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
# Element style: gcd(a,b)-> a*x + b*y = r = gcd(a,b) | ||
|
||
# Inverse of elements if gcd(a,b)==1: | ||
# * a^-1 mod (b) = x mod(b) | ||
# * b^-1 mod (a) = y mod(a) | ||
|
||
# Naming is according to Bézout's identity matching to that on Wikipedia | ||
|
||
|
||
def extended_euclidean_gcd(a, b): | ||
x, y, u, v = 0, 1, 1, 0 | ||
while a != 0: | ||
q, r = b//a, b % a | ||
m, n = x-u*q, y-v*q | ||
b, a, x, y, u, v = a, r, u, v, m, n | ||
|
||
gcd = b | ||
return gcd, x, y | ||
|
||
|
||
def main(): | ||
a, b = 26, 15 | ||
gcd, x, y = extended_euclidean_gcd(a, b) | ||
print("GCD of {} and {} is {}".format(a, b, gcd)) | ||
print("The Equation : {}*{} + {}*{} = {}".format(a, x, b, y, gcd)) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |