Skip to content

Commit 188cfb3

Browse files
authored
Fixing a small mistake with the linear congruence solver function
1 parent a2cacfe commit 188cfb3

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

ChineseRemainderTheorem

+9-12
Original file line numberDiff line numberDiff line change
@@ -58,17 +58,14 @@ def checkCoprime(relations):
5858
def extendedEuclideanAlgorithm(a, m):
5959
#Computes the Bezout coefficients s and t such that a*s + b*t = gcd(a, b).
6060
#Returns (s,t)
61-
s_prev, s = 1, 0
62-
t_prev, t = 0, 1
63-
r_prev, r = a, m
64-
65-
while r != 0:
66-
quotient = r_prev // r
67-
r_prev, r = r, r_prev - quotient * r
68-
s_prev, s = s, s_prev - quotient * s
69-
t_prev, t = t, t_prev - quotient * t
70-
71-
return r_prev, s_prev, t_prev
61+
if a == 0:
62+
return m, 0, 1
63+
gcd, s1, t1 = extendedEuclideanAlgorithm(m % a, a)
64+
65+
#update x and y using results of recursive call
66+
s = t1 - (m // a) * s1
67+
t = s1
68+
return gcd, s, t
7269

7370
def solveLinearCongruence(a, r, m):
7471
#Solves the linear congruence equation ax ≡ r mod m, where a, r, and m are integers.
@@ -117,7 +114,7 @@ def solve(relations):
117114
print("\nCalculating Si:")
118115
#The linear congruence relation to solve is: Mi*Si ≡ 1 mod mi >> Si needs to be found.
119116
for i in range(size):
120-
S_list[i] = solveLinearCongruence(M_list[i], relations[i][0], relations[i][1])
117+
S_list[i] = solveLinearCongruence(M_list[i], 1, relations[i][1])
121118
print(f"The solution of the linear congruence: {M_list[i]}∙S{i+1}≡1mod{relations[i][1]} is: S{i+1}={S_list[i]}mod{relations[i][1]}")
122119

123120
#finding x0: x0 ≡ (M1*S1*r1 + M2*S2*r2 + ... + Mi*Si*ri) mod M

0 commit comments

Comments
 (0)