Solve for .
The theorem
Let .
- If → no solution.
- If → exactly solutions modulo , forming an arithmetic progression with common difference .
To find them: divide through by ,
where now , so the inverse exists:
The full solution set is for .
Code
// all solutions of a*x = b (mod m), as {smallest solution, step}; {-1,-1} if none
pair<long long,long long> linearCongruence(long long a, long long b, long long m) {
a = ((a % m) + m) % m;
b = ((b % m) + m) % m;
long long x, y;
long long g = extgcd(a, m, x, y);
if (b % g) return {-1, -1};
long long mod = m / g;
long long x0 = (__int128)(x % mod) * (b / g) % mod;
x0 = (x0 % mod + mod) % mod;
return {x0, mod}; // solutions: x0, x0+mod, ..., x0+(g-1)*mod
}The __int128 guards against overflow when is near .
Systems of congruences
- Coprime moduli → CRT gives a unique solution modulo .
- Non-coprime moduli → merge pairwise. The system , has a solution iff , and then the merged congruence has modulus .
// merge x = r1 (mod m1) and x = r2 (mod m2)
pair<long long,long long> crtMerge(long long r1, long long m1, long long r2, long long m2) {
long long p, q;
long long g = extgcd(m1, m2, p, q);
if ((r2 - r1) % g) return {-1, -1}; // inconsistent
long long lcm = m1 / g * m2;
long long t = (__int128)((r2 - r1) / g) * p % (m2 / g);
long long r = ((__int128)m1 * t + r1) % lcm;
return {(r % lcm + lcm) % lcm, lcm};
}Fold this over a list of congruences to solve an arbitrary system, or report inconsistency.
Related equations
| Equation | Method |
|---|---|
| this page | |
| over | linear Diophantine |
| CRT / the merge above | |
| quadratic residues, Tonelli-Shanks | |
| discrete logarithm | |
| discrete root | |
| solve mod , then Hensel lift |
Where it shows up
- Modular division — is exactly .
- Cycle alignment — “two events repeat every and steps; when do they coincide?”
- Calendar and clock problems.
- Reconstructing a value from residues — CRT, used to avoid big-integer arithmetic by working modulo several primes and recombining.
- Frobenius / coin problems — feasibility of modulo the smallest coin.
The three-step recipe
- Compute .
- If , report no solution.
- Divide , and by , invert, and enumerate the solutions.
Forgetting step 3’s ” solutions” is the usual mistake — problems often ask for the count or for the smallest positive solution, and there is more than one.
See also: Modular Inverse · CRT · Linear Diophantine Equations