I am implementing an extended Eucilid algorithm with matrix mod N
. This is my code implementation:
JavaScript
x
26
26
1
def eea(a, b):
2
if not isinstance(a, int) or not isinstance(b, int) or not a or not b:
3
result = 'Error(eea): Invalid input num'
4
else:
5
original_a = a
6
original_b = b
7
x, y, u, v = (0, 1, 1, 0)
8
while a != 0:
9
q, r = (b // a, b % a)
10
m, n = (x - u * q, y - v * q)
11
b, a, x, y, u, v = (a, r, u, v, m, n)
12
cnsm = b
13
result = [cnsm, x, y]
14
if original_a < 0 and original_b < 0:
15
result[0] = abs(result[0])
16
result[1] = -1 * result[1]
17
result[2] = -1 * result[2]
18
if result[0] < 0:
19
result = [abs(result[0]), x, y]
20
if original_a < 0 < original_b or original_b < 0 < original_a:
21
result[2] = -1 * result[2]
22
if result[0] > 0:
23
if original_b < 0 < original_a:
24
result[2] = -1 * result[2]
25
return result
26
Now, I need to calculate the matrix inverse mod 36
with the following matrix:
JavaScript
1
3
1
[3, 2]
2
[4, 7]
3
(This is the video link:)
However, my code can only get x = -11, y = -4
, exactly it is a solution of equation 13x = 36y + 1
, but in the video the solution is x = 25, y = 9
, so how do I change my code to meet this situation?
Advertisement
Answer
−11 is congruent to 25 mod 36, so in Python you can just take x % N
.