-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
59 lines (45 loc) · 1.26 KB
/
main.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
"""Multivariable Chinese Remainder Theorem"""
from math import gcd
import numpy as np
def egcd(a, m):
"""Extended GCD"""
if a == 0:
return (m, 0, 1)
g, y, x = egcd(m % a, a)
return (g, x - (m // a) * y, y)
def modinv(a, m):
"""Find Modular Inverse"""
amodm = a % m
g, x, _ = egcd(amodm, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def pivot(A, m):
"""Finds the pivot of A and m"""
length = len(A)
result = [0] * length
for i in range(length):
for j in range(length):
if gcd(A[i][j], m[i]) == 1:
result[i] = j
return result
def is_sol(A, x, b, m):
"""Checks if Ax = b mod m"""
ax_b = np.matmul(np.array(A), np.array(x)) - np.array(b)
for i, mod in enumerate(m):
if ax_b[i] % mod != 0:
return False
return True
def mcrt(A, b, m):
"""Returns for x in Ax = b mod m"""
eqn_cnt = len(A)
piv = pivot(A, m)
x = [0] * eqn_cnt
m_prod = 1
for i in range(eqn_cnt):
tot = sum(A[i][k] * x[k] for k in range(eqn_cnt))
tmp = (modinv(m_prod * A[i][piv[i]], m[i]) * (b[i] - tot)) % m[i]
x[piv[i]] = x[piv[i]] + tmp * m_prod
m_prod *= m[i]
return x