Why: every integer combination ax+by is a multiple of g=gcd(a,b) (forward), and Bézout’s identity produces ax+by=g, which scales to any multiple of g (converse).
Finding all solutions
Run extended Euclid to get x0,y0 with ax0+by0=g.
Scale: x1=x0⋅(c/g), y1=y0⋅(c/g).
The general solution is x=x1+k⋅gb,y=y1−k⋅ga,k∈Z.
// returns false if no solution; otherwise fills one solution and the step sizesbool 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 x≥0: x1+kgb≥0⟹k≥⌈b−x1g⌉.
Both x≥0 and y≥0: intersect the two ranges of k; the number of integer k 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 −4. 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 x+y
Since x+y=x1+y1+k(gb−a), the sum is linear in k: push k to whichever end of its feasible interval the sign of (b−a) favours. Check both endpoints — the feasible k range is an interval, so the extremes are the only candidates.
More variables
a1x1+⋯+anxn=c has a solution iff gcd(a1,…,an)∣c. Solve iteratively: let g2=gcd(a1,a2) and solve g2t+a3x3+⋯=c, then unwind t into x1,x2.
Related: the Frobenius problem
“What is the largest cnot representable as a non-negative combination?”
Two coprime coinsa,b: the answer is ab−a−b (the Chicken McNugget theorem), and exactly 2(a−1)(b−1) 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 1018.