Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/shared/crt.py
2587 views
1
from sage.all import crt
2
from math import lcm
3
4
5
def fast_crt(X, M, segment_size=8):
6
"""
7
Uses a divide-and-conquer algorithm to compute the CRT remainder and least common multiple.
8
:param X: the remainders
9
:param M: the moduli (not necessarily coprime)
10
:param segment_size: the minimum size of the segments (default: 8)
11
:return: a tuple containing the remainder and the least common multiple
12
"""
13
assert len(X) == len(M)
14
assert len(X) > 0
15
while len(X) > 1:
16
X_ = []
17
M_ = []
18
for i in range(0, len(X), segment_size):
19
if i == len(X) - 1:
20
X_.append(X[i])
21
M_.append(M[i])
22
else:
23
X_.append(crt(X[i:i + segment_size], M[i:i + segment_size]))
24
M_.append(lcm(*M[i:i + segment_size]))
25
X = X_
26
M = M_
27
28
return X[0], M[0]
29
30