import
java.util.ArrayList;
import
java.math.BigInteger;
public
class
ChineseRemainderTheorem {
public
static
BigInteger modinv(BigInteger a, BigInteger m) {
BigInteger m0 = m;
BigInteger y = BigInteger.ZERO;
BigInteger x = BigInteger.ONE;
if
(m.equals(BigInteger.ONE))
return
BigInteger.ZERO;
while
(a.compareTo(BigInteger.ONE) ==
1
) {
BigInteger q = a.divide(m);
BigInteger t = m;
m = a.mod(m);
a = t;
t = y;
y = x.subtract(q.multiply(y));
x = t;
}
if
(x.compareTo(BigInteger.ZERO) == -
1
)
x = x.add(m0);
return
x;
}
public
static
BigInteger crt(ArrayList<BigInteger> m, ArrayList<BigInteger> x) {
BigInteger M = BigInteger.ONE;
for
(
int
i =
0
; i < m.size(); i++) {
M = M.multiply(m.get(i));
}
BigInteger result = BigInteger.ZERO;
for
(
int
i =
0
; i < m.size(); i++) {
BigInteger Mi = M.divide(m.get(i));
BigInteger MiInv = modinv(Mi, m.get(i));
result = result.add(x.get(i).multiply(Mi).multiply(MiInv));
}
return
result.mod(M);
}
public
static
void
main(String[] args) {
ArrayList<BigInteger> m =
new
ArrayList<>();
ArrayList<BigInteger> x =
new
ArrayList<>();
m.add(BigInteger.valueOf(
4
));
m.add(BigInteger.valueOf(
7
));
m.add(BigInteger.valueOf(
9
));
m.add(BigInteger.valueOf(
11
));
x.add(BigInteger.valueOf(
3
));
x.add(BigInteger.valueOf(
4
));
x.add(BigInteger.valueOf(
1
));
x.add(BigInteger.valueOf(
0
));
System.out.println(crt(m, x));
}
}