extended euclidean algorithm Algorithm
The extended Euclidean algorithm is an extension of the Euclidean algorithm, which computes not only the greatest common divisor (GCD) of two integers a and b, but also the coefficients of Bézout's identity, which are integers x and y such that ax + by = gcd(a, b). It is a fundamental and efficient algorithm in number theory and has various applications in cryptography, coding theory, and computational geometry. The extended Euclidean algorithm can also be used to find the multiplicative inverse of a number modulo another number, which is essential in the RSA encryption and decryption process.
The algorithm works by performing a series of divisions and maintaining a pair of equations for each step, which is derived from the previous step's equations. The initial equations are x1 = 1, y1 = 0, and x2 = 0, y2 = 1. At each step, the algorithm divides the current dividend by the current divisor and uses the remainder as the new divisor for the next step. The new coefficients for Bézout's identity are calculated by subtracting the product of the quotient and the previous coefficients from the older coefficients. The algorithm proceeds until the remainder becomes zero, and the last non-zero remainder is the GCD of the two numbers. The corresponding coefficients of Bézout's identity are the ones that were used to calculate this GCD.
"""
Extended Euclidean Algorithm.
Finds 2 numbers a and b such that it satisfies
the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity)
"""
# @Author: S. Sharma <silentcat>
# @Date: 2019-02-25T12:08:53-06:00
# @Email: [email protected]
# @Last modified by: PatOnTheBack
# @Last modified time: 2019-07-05
import sys
def extended_euclidean_algorithm(m, n):
"""
Extended Euclidean Algorithm.
Finds 2 numbers a and b such that it satisfies
the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity)
"""
a = 0
a_prime = 1
b = 1
b_prime = 0
q = 0
r = 0
if m > n:
c = m
d = n
else:
c = n
d = m
while True:
q = int(c / d)
r = c % d
if r == 0:
break
c = d
d = r
t = a_prime
a_prime = a
a = t - q * a
t = b_prime
b_prime = b
b = t - q * b
pair = None
if m > n:
pair = (a, b)
else:
pair = (b, a)
return pair
def main():
"""Call Extended Euclidean Algorithm."""
if len(sys.argv) < 3:
print("2 integer arguments required")
exit(1)
m = int(sys.argv[1])
n = int(sys.argv[2])
print(extended_euclidean_algorithm(m, n))
if __name__ == "__main__":
main()