Skip to content

Commit 9db6f67

Browse files
committed
improve naming of variables
1 parent 478b0ac commit 9db6f67

File tree

1 file changed

+20
-36
lines changed

1 file changed

+20
-36
lines changed

maths/extended_euclidean_algorithm.py

Lines changed: 20 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -16,28 +16,6 @@
1616
import sys
1717

1818

19-
def sign(n: int) -> int:
20-
"""
21-
Returns sign of number for correction of negative numbers in algorithm
22-
23-
>>> sign(4)
24-
1
25-
26-
>>> sign(0)
27-
0
28-
29-
>>> sign(-8)
30-
-1
31-
32-
"""
33-
if n > 0:
34-
return 1
35-
elif n < 0:
36-
return -1
37-
else:
38-
return 0
39-
40-
4119
def extended_euclidean_algorithm(a: int, b: int) -> (int, int):
4220
"""
4321
Extended Euclidean Algorithm.
@@ -67,23 +45,29 @@ def extended_euclidean_algorithm(a: int, b: int) -> (int, int):
6745
(1, 0)
6846
6947
"""
70-
old_r, r = a, b
71-
old_s, s = 1, 0
72-
old_t, t = 0, 1
48+
# base cases
49+
if abs(a) == 1:
50+
return a, 0
51+
elif abs(b) == 1:
52+
return 0, b
53+
54+
old_remainder, remainder = a, b
55+
old_coeff_a, coeff_a = 1, 0
56+
old_coeff_b, coeff_b = 0, 1
7357

74-
while r != 0:
75-
quotient = old_r // r
76-
old_r, r = r, old_r - quotient * r
77-
old_s, s = s, old_s - quotient * s
78-
old_t, t = t, old_t - quotient * t
58+
while remainder != 0:
59+
quotient = old_remainder // remainder
60+
old_remainder, remainder = remainder, old_remainder - quotient * remainder
61+
old_coeff_a, coeff_a = coeff_a, old_coeff_a - quotient * coeff_a
62+
old_coeff_b, coeff_b = coeff_b, old_coeff_b - quotient * coeff_b
7963

8064
# sign correction for negative numbers
81-
if abs(a) == 1:
82-
return sign(a), 0
83-
elif abs(b) == 1:
84-
return 0, sign(b)
85-
else:
86-
return (sign(a) * old_s, sign(b) * old_t)
65+
if a < 0:
66+
old_coeff_a = -old_coeff_a
67+
if b < 0:
68+
old_coeff_b = -old_coeff_b
69+
70+
return old_coeff_a, old_coeff_b
8771

8872

8973
def main():

0 commit comments

Comments
 (0)