Linear Diophantine equations

Linear Diophantine equations

Equations to be solved in whole numbers. A linear one in many unknowns has a lattice of solutions, given by a basis; asking for non-negative solutions turns it into the coin problem, with its largest unpayable amount.

All the solutions at once

a1x1+⋯+anxn=ca_1x_1 + \dots + a_nx_n = c has an integer solution exactly when g=gcd⁡(a1,…,an)g = \gcd(a_1, \dots, a_n) divides cc (Bézout). The solutions are then a particular one plus any integer combination of n−1n - 1 basis vectors of the homogeneous solutions. The basis is found by unimodular column operations, the extended Euclidean algorithm run on a whole row, so it is a true lattice basis: every solution is reached, with integer coefficients.

import { linearDiophantine, nonNegativeSolutions, frobenius, coinWays, egyptianGreedy, egyptianShortest } from "@ratmath/numtheory";

linearDiophantine([6, 10, 15], 1);
// { solvable: true, g: 1n, particular: [-14n, 7n, 1n], basis: [[-5n, 3n, 0n], [-30n, 15n, 2n]] }
linearDiophantine([4, 6], 5);   // { solvable: false, g: 2n, reason: "gcd = 2 does not divide 5" }
nonNegativeSolutions(5, 7, 100);   // { solutions: [[6n, 10n], [13n, 5n], [20n, 0n]] }

The coin problem

With coins of values a1,…,ana_1, \dots, a_n (gcd 1), every large enough amount can be paid. The largest that cannot is the Frobenius number. For two coins Sylvester found ab−a−bab - a - b. For more there is no formula, but there is an algorithm: for each residue rr modulo the smallest coin a1a_1, find the smallest payable amount ≡r\equiv r, a shortest path in a graph on the residues; the Frobenius number is the largest of those, minus a1a_1.

frobenius([3, 5]);         // 7n
frobenius([6, 9, 20]);     // 43n: the McNugget number
coinWays(100, [1, 5, 10, 25]);    // 242n ways to change a dollar

coinWays counts with the generating function ∏i1/(1−xai)\prod_i 1/(1 - x^{a_i}), adding one coin at a time.

Egyptian fractions

Every positive fraction is a sum of distinct unit fractions. The greedy method (Fibonacci, Sylvester) takes the largest 1/n1/n that fits: since the numerator of what is left strictly drops, it ends, but the denominators can explode. A search finds a shortest expansion instead.

egyptianGreedy("4/13");     // [4n, 18n, 468n]
egyptianShortest("4/13");   // [4n, 26n, 52n]
egyptianGreedy("5/121");    // [25n, 757n, 763309n, 873960180913n, 1527612795642093418846225n]
egyptianShortest("5/121");  // [33n, 121n, 363n]

Erdős and Straus conjectured that 4/n4/n always needs at most three terms; it has been checked far beyond any nn one could type here.

Try itEdit the code and run it with @ratmath/numtheory and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs