Problem 360
Solve Two Congruences
Hard · 30 pts · Math, Number Theory
Problem
Find the smallest non-negative integer X that satisfies both X mod M1 = A1 and X mod M2 = A2. The moduli do not have to be coprime, so a solution may not exist; in that case print -1. This is the Chinese Remainder Theorem for two equations: a solution exists exactly when A1 and A2 leave the same remainder modulo gcd(M1, M2), and it is unique modulo lcm(M1, M2). The extended Euclidean algorithm finds it. Some values computed along the way can be larger than a 32-bit int can hold (about 2.1 × 10^9), even when the input looks small, so use a 64-bit integer type: long long in C++, long in Java (Python needs nothing special).
Input
Four integers A1, M1, A2 and M2.
Output
Print the smallest non-negative X, or -1 if none exists.
Constraints
1 <= M1, M2 <= 1000000000; 0 <= A1 < M1; 0 <= A2 < M2
Example input
2 3 3 5
Example output
8
Explanation
We need X mod 3 = 2 and X mod 5 = 3. The numbers that leave remainder 3 when divided by 5 are 3, 8, 13, ... The first, 3, leaves remainder 0 when divided by 3, but 8 leaves remainder 2, so the smallest answer is 8.