Chinese Remainder Theorem¶
source https://www.geeksforgeeks.org/Method 1¶
Pengecekan nilai satu-persatu
Time Complexity : O(M)
def findMinX(num, rem, k):
x = 1
while(True):
j = 0
while(j < k):
if (x % num[j] != rem[j]):
break
j += 1
if (j == k):
return x
x += 1
num = [3, 4, 5]
rem = [2, 3, 1]
k = len(num)
print("x is", findMinX(num, rem, k))
Method 2¶
Recommended
Time Complexity : O(N*LogN)
from Crypto.Util.number import inverse
def findMinX(num, rem, k) :
prod = 1
for i in range(0, k) :
prod = prod * num[i]
result = 0
for i in range(0,k):
pp = prod // num[i]
result = result + rem[i] * inverse(pp, num[i]) * pp
return result % prod
num = [3, 4, 5]
rem = [2, 3, 1]
k = len(num)
print( "x is " , findMinX(num, rem, k))