|
16 | 16 | import sys
|
17 | 17 |
|
18 | 18 |
|
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 |
| - |
41 | 19 | def extended_euclidean_algorithm(a: int, b: int) -> (int, int):
|
42 | 20 | """
|
43 | 21 | Extended Euclidean Algorithm.
|
@@ -67,23 +45,29 @@ def extended_euclidean_algorithm(a: int, b: int) -> (int, int):
|
67 | 45 | (1, 0)
|
68 | 46 |
|
69 | 47 | """
|
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 |
73 | 57 |
|
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 |
79 | 63 |
|
80 | 64 | # 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 |
87 | 71 |
|
88 | 72 |
|
89 | 73 | def main():
|
|
0 commit comments