From a7ef7b7df48e0a1b66a0fa2d3ebb76290d43ca3c Mon Sep 17 00:00:00 2001 From: A Silent Cat Date: Mon, 25 Feb 2019 12:37:22 -0600 Subject: [PATCH 1/2] Added extended euclidean algorithm --- Maths/extended_euclidean_algorithm.py | 40 +++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Maths/extended_euclidean_algorithm.py diff --git a/Maths/extended_euclidean_algorithm.py b/Maths/extended_euclidean_algorithm.py new file mode 100644 index 000000000000..fd6491987def --- /dev/null +++ b/Maths/extended_euclidean_algorithm.py @@ -0,0 +1,40 @@ +# @Author: S. Sharma +# @Date: 2019-02-25T12:08:53-06:00 +# @Email: silentcat@protonmail.com +# @Last modified by: silentcat +# @Last modified time: 2019-02-25T12:36:52-06:00 + +import sys + +# Finds 2 numbers a and b such that it satisfies +# the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) +def extended_euclidean_algorithm(m, n): + a = 1; aprime = 0; b = 0; bprime = 1 + q = 0; r = 1 + c = m; d = n + + while r != 0: + q = c / d + r = c % d + c = n + d = r + + t = a + a = aprime + aprime = int(t - q*a) + + t = b + b = bprime + bprime = int(t - q*b) + return (a, b) + +def main(): + 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() From 67254c861c17486cb2b853ab2a647a9fdfced22a Mon Sep 17 00:00:00 2001 From: A Silent Cat Date: Tue, 26 Feb 2019 07:08:09 -0600 Subject: [PATCH 2/2] Fixed extended euclidean algorithm --- Maths/extended_euclidean_algorithm.py | 39 +++++++++++++++++---------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/Maths/extended_euclidean_algorithm.py b/Maths/extended_euclidean_algorithm.py index fd6491987def..f5a3cc88e474 100644 --- a/Maths/extended_euclidean_algorithm.py +++ b/Maths/extended_euclidean_algorithm.py @@ -2,31 +2,42 @@ # @Date: 2019-02-25T12:08:53-06:00 # @Email: silentcat@protonmail.com # @Last modified by: silentcat -# @Last modified time: 2019-02-25T12:36:52-06:00 +# @Last modified time: 2019-02-26T07:07:38-06:00 import sys # Finds 2 numbers a and b such that it satisfies # the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) def extended_euclidean_algorithm(m, n): - a = 1; aprime = 0; b = 0; bprime = 1 - q = 0; r = 1 - c = m; d = n + a = 0; aprime = 1; b = 1; bprime = 0 + q = 0; r = 0 + if m > n: + c = m; d = n + else: + c = n; d = m - while r != 0: - q = c / d + while True: + q = int(c / d) r = c % d - c = n + if r == 0: + break + c = d d = r - t = a - a = aprime - aprime = int(t - q*a) + t = aprime + aprime = a + a = t - q*a - t = b - b = bprime - bprime = int(t - q*b) - return (a, b) + t = bprime + bprime = b + b = t - q*b + + pair = None + if m > n: + pair = (a,b) + else: + pair = (b,a) + return pair def main(): if len(sys.argv) < 3: