Solve over the integers.

Solvability

A solution exists iff .

Why: every integer combination is a multiple of (forward), and Bézout’s identity produces , which scales to any multiple of (converse).

Finding all solutions

  1. Run extended Euclid to get with .
  2. Scale: , .
  3. The general solution is
// returns false if no solution; otherwise fills one solution and the step sizes
bool diophantine(long long a, long long b, long long c,
                 long long& x, long long& y, long long& g) {
    g = extgcd(llabs(a), llabs(b), x, y);
    if (c % g) return false;
    x *= c / g; y *= c / g;
    if (a < 0) x = -x;
    if (b < 0) y = -y;
    return true;                      // steps: x += b/g, y -= a/g
}

Constrained solutions

Most problems ask for solutions in a range, or for the count, or for an extremum. All follow from the parametrisation.

Solutions with :

Both and : intersect the two ranges of ; the number of integer in the intersection is the answer.

// count solutions with x in [xl, xr] and y in [yl, yr]
long long countSolutions(long long a, long long b, long long c,
                         long long xl, long long xr, long long yl, long long yr) {
    long long x, y, g;
    if (!diophantine(a, b, c, x, y, g)) return 0;
    long long dx = b / g, dy = a / g;
    // shift k so that x in [xl, xr] and y in [yl, yr]; intersect the two k-intervals
    // (compute k bounds with careful floor/ceil division)
    ...
}

Floor division with negatives

C++ truncates toward zero, so (-7) / 2 == -3, not . Write explicit helpers:

long long fdiv(long long a, long long b) { return a / b - ((a % b != 0) && ((a < 0) != (b < 0))); }
long long cdiv(long long a, long long b) { return a / b + ((a % b != 0) && ((a < 0) == (b < 0))); }

Nearly every wrong answer in this topic traces back to this.

Minimising

Since , the sum is linear in : push to whichever end of its feasible interval the sign of favours. Check both endpoints — the feasible range is an interval, so the extremes are the only candidates.

More variables

has a solution iff . Solve iteratively: let and solve , then unwind into .

“What is the largest not representable as a non-negative combination?”

  • Two coprime coins : the answer is (the Chicken McNugget theorem), and exactly values are unrepresentable.
  • Three or more: no closed form; computing it is NP-hard in general. For small coin values, the “Dijkstra on residues” technique answers representability for targets up to .

Where these appear

ProblemEquation
Jug pouring / measuring
”Can I make exactly with steps of and ?“with
Modular division is
Lattice points on a line segment points, from the same theory
Aligning two periodic eventsCRT, which reduces to a Diophantine equation
Scheduling with two step sizescount solutions in a range

See also: Extended Euclidean · Linear Congruence · Coin Change