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
has an integer solution exactly when divides (Bézout). The solutions are then a particular one plus any integer combination of 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 (gcd 1), every large enough amount can be paid. The largest that cannot is the Frobenius number. For two coins Sylvester found . For more there is no formula, but there is an algorithm: for each residue modulo the smallest coin , find the smallest payable amount , a shortest path in a graph on the residues; the Frobenius number is the largest of those, minus .
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 , 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 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 always needs at most three terms; it has been checked far beyond any one could type here.
@ratmath/numtheory and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.