-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
/
Copy pathextended_euclidean_algorithm.py
100 lines (73 loc) · 1.97 KB
/
extended_euclidean_algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"""
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)
https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
"""
# @Author: S. Sharma <silentcat>
# @Date: 2019-02-25T12:08:53-06:00
# @Email: [email protected]
# @Last modified by: pikulet
# @Last modified time: 2020-10-02
import sys
def sign(n: int) -> int:
"""
Returns sign of number for correction of negative numbers in algorithm
>>> sign(4)
1
>>> sign(0)
0
>>> sign(-8)
-1
"""
if n > 0:
return 1
elif n < 0:
return -1
else:
return 0
def extended_euclidean_algorithm(a: int, b: int) -> (int, int):
"""
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)
>>> extended_euclidean_algorithm(1, 24)
(1, 0)
>>> extended_euclidean_algorithm(8, 14)
(2, -1)
>>> extended_euclidean_algorithm(240, 46)
(-9, 47)
>>> extended_euclidean_algorithm(1, -4)
(1, 0)
>>> extended_euclidean_algorithm(-2, -4)
(-1, 0)
>>> extended_euclidean_algorithm(0, -4)
(0, -1)
>>> extended_euclidean_algorithm(2, 0)
(1, 0)
"""
old_r, r = a, b
old_s, s = 1, 0
old_t, t = 0, 1
while r != 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient * t
# sign correction for negative numbers
if abs(a) == 1:
return sign(a), 0
elif abs(b) == 1:
return 0, sign(b)
else:
return (sign(a) * old_s, sign(b) * old_t)
def main():
"""Call Extended Euclidean Algorithm."""
if len(sys.argv) < 3:
print("2 integer arguments required")
exit(1)
a = int(sys.argv[1])
b = int(sys.argv[2])
print(extended_euclidean_algorithm(a, b))
if __name__ == "__main__":
main()