Skip to content

Commit fd06b1a

Browse files
Fermat's little theorem and the freshman's dream, for every prime (#1502)
Under a quantifier that establishes p prime, p divides d where writing each power (u + v)^p in d as u^p + v^p leaves nothing: what the binomial theorem adds are multiples of binomial(p, k) with 0 < k < p, and the rule asks the quantifiers for that first (add_pow_char, resting on Nat.Prime.dvd_choose_self). A congruence reads the same rule. A congruence modulo a symbol, or an equation of residues, over a row of whole numbers holds where it holds at one member and the difference of its sides changes by a multiple of the modulus from each member to the next (Int.inductionOn'). For a^p = a (mod p) that change is (a + 1)^p - a^p - 1, which the binomial theorem reads. Sullivan and Mackey's Prob 8.9.25 and 8.9.26. Part of #1409. Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c11eabc commit fd06b1a

7 files changed

Lines changed: 244 additions & 5 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1540,6 +1540,24 @@ Quantifiers were a parse error in 2.5.0.
15401540
| `forall k in ZZ : forall p in PP : (0 < k and k < p) implies p divides binomial(p, k)` | `UnhandledParseException` | `True` |
15411541
| `forall p in PP : forall k in ZZ+ : k < p implies p divides binomial(p, k)` | `UnhandledParseException` | `True` |
15421542

1543+
### Fermat's little theorem and the freshman's dream, for every prime
1544+
1545+
`forall p in PP : forall a in ZZ : a^p = a (mod p)` was left as written. Under a quantifier that
1546+
establishes `p` prime, `p divides d` now holds where writing each power `(u + v)^p` in `d` as
1547+
`u^p + v^p` leaves nothing: the binomial theorem adds only multiples of `binomial(p, k)` with
1548+
`0 < k < p`, each a multiple of `p`. A congruence modulo a symbol, or an equation of residues, over
1549+
a row of whole numbers holds where it holds at one member and the difference of its sides changes
1550+
by a multiple of the modulus from each member to the next. For Fermat's little theorem that change
1551+
is `(a + 1)^p - a^p - 1`. These are Sullivan and Mackey's Prob 8.9.25 and 8.9.26
1552+
([#1409](https://github.com/asc-community/AngouriMath/issues/1409)). Quantifiers were a parse error
1553+
in 2.5.0.
1554+
1555+
| Input | Was (2.5.0) | Now |
1556+
|---|---|---|
1557+
| `forall p in PP : forall a in ZZ : a^p = a (mod p)` | `UnhandledParseException` | `True` |
1558+
| `forall p in PP : forall a in ZZ : a^p mod p = a mod p` | `UnhandledParseException` | `True` |
1559+
| `forall p in PP : forall a, b in ZZ : (a + b)^p = a^p + b^p (mod p)` | `UnhandledParseException` | `True` |
1560+
15431561
### `binomial(n, k)` is a function
15441562

15451563
**Addition, not silent.** The binomial coefficient is a node, `Entity.Binomialf`, spelled

‎Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariatePolynomial.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ internal static MultivariatePolynomial Monomial(int variableCount, int variable)
123123

124124
private static int ShiftOf(int variable) => (MaxVariables - 1 - variable) * BitsPerVariable;
125125

126-
private static int PowerOf(ulong monomial, int variable)
126+
internal static int PowerOf(ulong monomial, int variable)
127127
=> (int)((monomial >> ShiftOf(variable)) & PowerMask);
128128

129129
private static ulong Pack(int variable, int power) => (ulong)power << ShiftOf(variable);

‎Sources/AngouriMath/Functions/Boolean/QuantifierFacts.cs‎

Lines changed: 89 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -193,10 +193,16 @@ internal static Entity Renamed(Entity expression, Variable from, Variable to)
193193

194194
/// <summary>
195195
/// Whether a rule reads the facts at <paramref name="node"/>, which is what a body is
196-
/// renamed and decided with the facts in scope for.
196+
/// renamed and decided with the facts in scope for: a divisibility, a congruence or an
197+
/// equation of residues by a modulus that is not a number, which the rules modulo a
198+
/// prime read.
197199
/// </summary>
198-
private static bool Reads(Entity node)
199-
=> node is Dividesf(var divisor, Binomialf(var upper, _)) && divisor == upper;
200+
private static bool Reads(Entity node) => node switch
201+
{
202+
Dividesf(not Number, _) or Congruentf(_, _, not Number) => true,
203+
Equalsf(Modf(_, var modulus), Modf(_, var other)) => modulus is not Number && modulus == other,
204+
_ => false
205+
};
200206

201207
private static bool MentionsARenamedName(Entity expression)
202208
{
@@ -233,6 +239,86 @@ internal static bool PrimeDividesItsBinomial(Entity p, Entity k)
233239
return true;
234240
}
235241

242+
/// <summary>
243+
/// Whether <c>p divides d</c> by the binomial theorem, with the facts in scope: <c>p</c> is
244+
/// prime, <c>d</c> is a polynomial with whole coefficients in whole quantities, and
245+
/// writing each power <c>(u + v)^p</c> in it as <c>u^p + v^p</c> leaves nothing, or only
246+
/// multiples of <c>p</c>. What the binomial theorem adds to <c>u^p + v^p</c> is
247+
/// <c>binomial(p, k) u^k v^(p - k)</c> for <c>0 &lt; k &lt; p</c>, each a multiple of
248+
/// <c>p</c> by <see cref="PrimeDividesItsBinomial"/>. That is asked of the quantifiers
249+
/// first, and recorded as the step this one rests on. A difference is read the same way,
250+
/// since <c>(-v)^p</c> is <c>-v^p</c> modulo every prime, 2 included. Sullivan and
251+
/// Mackey's Prob 8.9.25, the freshman's dream.
252+
/// </summary>
253+
internal static bool PrimeDividesByTheBinomialTheorem(Entity p, Entity d)
254+
{
255+
if (top is null || !IsPrime(p) || !d.Nodes.Any(node => node is Powf(Sumf or Minusf, var exponent) && exponent == p))
256+
return false;
257+
var dreamt = d.Replace(node => node is Powf(Sumf or Minusf, var exponent) && exponent == p ? PowersOfTheTerms(((Powf)node).Base, p) : node);
258+
// Read as polynomials over the same atoms, each of which must be the p-th power of a
259+
// whole quantity for a congruence modulo p to carry through a product with it.
260+
var atoms = new Dictionary<Entity, Variable>();
261+
var unfolded = new Dictionary<Entity, Entity>();
262+
var before = Quantifiers.Atomized(d, atoms, unfolded);
263+
var after = Quantifiers.Atomized(dreamt, atoms, unfolded);
264+
foreach (var atom in atoms.Keys)
265+
if (atom is not Powf(var @base, var exponent) || exponent != p || !IsWholePolynomial(@base))
266+
return false;
267+
var names = before.Vars.Concat(after.Vars).Distinct().ToArray();
268+
if (names.Length > MultivariatePolynomial.MaxVariables || names.Any(name => !atoms.ContainsValue(name) && !IsWhole(name)))
269+
return false;
270+
var indices = new Dictionary<Variable, int>();
271+
for (var i = 0; i < names.Length; i++)
272+
indices[names[i]] = i;
273+
if (MultivariatePolynomial.TryParse(before, indices) is not { HasIntegerCoefficients: true }
274+
|| MultivariatePolynomial.TryParse(after, indices) is not { } left
275+
|| !(left.IsZero || p is Variable modulus && indices.TryGetValue(modulus, out var at) && left.HasIntegerCoefficients && left.Terms.All(term => MultivariatePolynomial.PowerOf(term.Key, at) > 0)))
276+
return false;
277+
// The step this rests on, p divides binomial(p, k) for 0 < k < p, asked of the
278+
// quantifiers with the facts that p is prime already in scope.
279+
var k = (d + p).Vars.Any(name => name.Name == "k") ? Variable.CreateUnique(d + p, "k") : MathS.Var("k");
280+
ProofRecording.Enter();
281+
Entity binomials;
282+
try
283+
{
284+
binomials = new Forallf(k, MathS.Sets.Z, (Integer.Zero < k & k < p).Implies(new Dividesf(p, new Binomialf(p, k)))).InnerSimplified;
285+
}
286+
finally
287+
{
288+
ProofRecording.Leave();
289+
}
290+
if (binomials != Entity.Boolean.True)
291+
return false;
292+
if (ProofRecording.Recording)
293+
ProofRecording.AddBelow(new Dividesf(p, d),
294+
$"by the binomial theorem each ({string.Join("), (", d.Nodes.OfType<Powf>().Where(power => power.Base is Sumf or Minusf && power.Exponent == p).Select(power => power.Base).Distinct())})^{p} is the sum of the {p}-th powers of its terms and multiples of {p}, and what is left of {d} is a multiple of {p}",
295+
"add_pow_char", Entity.Boolean.True);
296+
return true;
297+
}
298+
299+
/// <summary>The p-th powers of the terms of a sum, added: <c>(u - v)^p</c> is read as <c>u^p - v^p</c>.</summary>
300+
private static Entity PowersOfTheTerms(Entity sum, Entity p)
301+
=> Sumf.LinearChildren(sum)
302+
.Select(term => term switch
303+
{
304+
Mulf(Integer { EInteger: var minusOne }, var rest) when minusOne.Equals(EInteger.FromInt32(-1)) => -rest.Pow(p).InnerSimplified,
305+
Integer { IsNegative: true } negative => -((Entity)(-negative)).Pow(p).InnerSimplified,
306+
_ => term.Pow(p).InnerSimplified
307+
})
308+
.Aggregate((left, right) => left + right);
309+
310+
/// <summary>Whether the expression is a polynomial with whole coefficients in names that are whole by the facts in scope.</summary>
311+
private static bool IsWholePolynomial(Entity expression)
312+
{
313+
var names = expression.Vars.Distinct().ToArray();
314+
if (names.Length > MultivariatePolynomial.MaxVariables || names.Any(name => !IsWhole(name)))
315+
return false;
316+
var indices = new Dictionary<Variable, int>();
317+
for (var i = 0; i < names.Length; i++)
318+
indices[names[i]] = i;
319+
return MultivariatePolynomial.TryParse(expression, indices) is { HasIntegerCoefficients: true };
320+
}
321+
236322
private static bool IsPrime(Entity expression)
237323
=> expression is Integer number ? Functions.Primes.IsPrime(number.EInteger) == true : IsIn(expression, 0);
238324

‎Sources/AngouriMath/Functions/Boolean/Quantifiers.cs‎

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,15 @@ private static Entity Quantified(Kind kind, Entity var, Entity over, Entity body
280280
: ($"by induction from {first}: the base case, and P({x} + 1) = c P({x}) + D with c >= 0 and D >= 0", "Nat.le_induction");
281281
return byGrowth;
282282
}
283+
// A congruence modulo a symbol, by the residue of the difference of its sides: the
284+
// same at one member and at the next along a row of whole numbers, so the same at
285+
// every member. Fermat's little theorem, Sullivan and Mackey's Prob 8.9.26.
286+
// https://github.com/asc-community/AngouriMath/issues/1409
287+
if (kind == Kind.All && set is SpecialSet row && IsIntegerSet(row) && ByTheResidueOfADifference(x, row, body, isExact, out var how) is { } byResidue)
288+
{
289+
by = how;
290+
return byResidue;
291+
}
283292
if (Witness(kind, x, set, body, isExact) is { } byWitness)
284293
{
285294
by = (byWitness == Entity.Boolean.False && kind == Kind.All ? "a member at which the body is false"
@@ -391,6 +400,86 @@ private static Entity Quantified(Kind kind, Entity var, Entity over, Entity body
391400
return Entity.Boolean.True.Provided((baseCondition & stepCondition).InnerSimplified(isExact));
392401
}
393402

403+
/// <summary>
404+
/// <c>forall x in S : f = g (mod m)</c>, or <c>f mod m = g mod m</c>, over a row of whole
405+
/// numbers, where <c>m</c> is not a number and does not mention <c>x</c>. With
406+
/// <c>D = f - g</c>: where <c>m</c> divides <c>D</c> at every member the statement holds.
407+
/// Otherwise, where it holds at one member and <c>m</c> divides <c>D(x + 1) - D(x)</c> at
408+
/// every member, <c>D</c> has one residue modulo <c>m</c> the whole way along the row, up
409+
/// from that member and down from it, so it holds at every member. Fermat's little
410+
/// theorem is the second, with the difference <c>(a + 1)^p - a^p - 1</c> read by the
411+
/// binomial theorem.
412+
/// </summary>
413+
private static Entity? ByTheResidueOfADifference(Variable x, SpecialSet set, Entity body, bool isExact, out (string Rule, string Lemma)? how)
414+
{
415+
how = null;
416+
var (difference, modulus) = body switch
417+
{
418+
Congruentf(var left, var right, var m) => (left - right, m),
419+
Equalsf(Modf(var left, var m), Modf(var right, var n)) when m == n => (left - right, m),
420+
_ => ((Entity?)null, (Entity?)null)
421+
};
422+
if (difference is null || modulus is null or Number || modulus.ContainsNode(x))
423+
return null;
424+
var tried = ProofRecording.Mark();
425+
if (Divides(modulus, difference, isExact, deeper: false))
426+
{
427+
how = ($"{modulus} divides {difference} at every member", "Int.modEq_iff_dvd");
428+
return Entity.Boolean.True;
429+
}
430+
ProofRecording.Rollback(tried);
431+
// A member at which the statement is decided: the least one, then 1, 0 and -1.
432+
Integer? start = null;
433+
foreach (var member in new[] { LeastMember(set), Integer.One, Integer.Zero, Integer.MinusOne }.OfType<Integer>().Distinct())
434+
{
435+
if (LeastMember(set) is { } least && member < least)
436+
continue;
437+
var at = body.Substitute(x, member).InnerSimplified(isExact);
438+
if (at == Entity.Boolean.False)
439+
{
440+
ProofRecording.AddBelow(body.Substitute(x, member), $"false at {member}, by evaluation", "decide", at);
441+
how = ($"false at {member}", "decide");
442+
return at;
443+
}
444+
if (at == Entity.Boolean.True)
445+
{
446+
ProofRecording.AddBelow(body.Substitute(x, member), $"the base case, at {member}, by evaluation", "decide", at);
447+
start = member;
448+
break;
449+
}
450+
}
451+
if (start is null)
452+
return null;
453+
var step = difference.Substitute(x, x + Integer.One) - difference;
454+
if (!Divides(modulus, step, isExact, deeper: true))
455+
{
456+
ProofRecording.Rollback(tried);
457+
return null;
458+
}
459+
ProofRecording.AddBelow(new Forallf(x, set, new Dividesf(modulus, step)), $"{modulus} divides the difference at {x} + 1 less the difference at {x}, at every member", "intro", Entity.Boolean.True);
460+
how = ($"by induction up and down from {start}: {modulus} divides the difference of the two sides there, and the difference changes by a multiple of {modulus} from each member to the next", "Int.inductionOn'");
461+
return Entity.Boolean.True;
462+
}
463+
464+
/// <summary>
465+
/// Whether <c>m divides d</c> simplifies to true, with what it rests on recorded under
466+
/// the decision, or <paramref name="deeper"/> under a step the caller records itself.
467+
/// </summary>
468+
private static bool Divides(Entity modulus, Entity difference, bool isExact, bool deeper)
469+
{
470+
if (deeper)
471+
ProofRecording.Enter();
472+
try
473+
{
474+
return new Dividesf(modulus, difference).InnerSimplified(isExact) == Entity.Boolean.True;
475+
}
476+
finally
477+
{
478+
if (deeper)
479+
ProofRecording.Leave();
480+
}
481+
}
482+
394483
private static bool IsUnboundedAbove(Intersectionf cut)
395484
=> (cut.Left as Interval ?? cut.Right as Interval) is { } interval && interval.Right.Evaled is Real { EDecimal: var end } && end.IsInfinity() && !end.IsNegative;
396485

@@ -975,7 +1064,7 @@ private static Dictionary<Entity, Entity> FactorialsUnfolded(Entity expr)
9751064
/// The expression with every maximal subterm that is not a sum, a difference, a product,
9761065
/// a whole power or a division replaced by one variable per distinct subterm.
9771066
/// </summary>
978-
private static Entity Atomized(Entity expr, Dictionary<Entity, Variable> atoms, Dictionary<Entity, Entity> unfolded)
1067+
internal static Entity Atomized(Entity expr, Dictionary<Entity, Variable> atoms, Dictionary<Entity, Entity> unfolded)
9791068
{
9801069
switch (expr)
9811070
{

‎Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,9 @@ protected override Entity InnerSimplify(bool isExact)
411411
// https://github.com/asc-community/AngouriMath/issues/1409
412412
(_, Binomialf(var upper, var lower)) when a == upper
413413
&& Functions.Boolean.QuantifierFacts.PrimeDividesItsBinomial(a, lower) => True,
414+
// And the binomial theorem modulo that prime: p divides (a + 1)^p - a^p - 1.
415+
// Sullivan and Mackey's Prob 8.9.25.
416+
(not Number, _) when Functions.Boolean.QuantifierFacts.PrimeDividesByTheBinomialTheorem(a, b) => True,
414417
(Number, Number) => MathS.NaN,
415418
_ => null
416419
},
@@ -451,6 +454,11 @@ protected override Entity InnerSimplify(bool isExact)
451454
case (Number, Number, Number):
452455
return MathS.NaN;
453456
}
457+
// (a + b)^p = a^p + b^p (mod p) for a prime p the quantifiers around establish,
458+
// by the binomial theorem. Sullivan and Mackey's Prob 8.9.25.
459+
// https://github.com/asc-community/AngouriMath/issues/1409
460+
if (modulus is not Number && Functions.Boolean.QuantifierFacts.PrimeDividesByTheBinomialTheorem(modulus, left - right))
461+
return Boolean.True;
454462
var difference = (left - right).InnerSimplified;
455463
if (difference is Integer whole && modulus is Integer m)
456464
return m.EInteger.IsZero

‎Sources/Tests/UnitTests/Core/ProofRecordingTest.cs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,20 @@ public void AFactTheQuantifiersEstablishIsReadUnderThem()
9898
Assert.All(steps, step => Assert.DoesNotContain("'", step.Rule));
9999
}
100100

101+
[Fact]
102+
public void FermatsLittleTheoremRestsOnTheBinomialTheorem()
103+
{
104+
var (verdict, steps) = Prove("forall p in PP : forall a in ZZ : a^p = a (mod p)");
105+
Assert.Equal(Entity.Boolean.True, verdict);
106+
// The induction, its base case at 1, and its step, which rests on the binomial
107+
// theorem modulo p, which rests on p dividing binomial(p, k) for 0 < k < p.
108+
Assert.Equal(new[] { "decide", "Nat.Prime.dvd_choose_self", "intro", "add_pow_char", "intro", "Int.inductionOn'", "intro" }, steps.Select(step => step.Lemma));
109+
Assert.Equal(new[] { 2, 5, 4, 3, 2, 1, 0 }, steps.Select(step => step.Depth));
110+
Assert.Equal("p divides binomial(p, k)".ToEntity(), steps[1].Statement);
111+
Assert.Equal("forall a in ZZ : a^p = a (mod p)".ToEntity(), steps[5].Statement);
112+
Assert.All(steps, step => Assert.DoesNotContain("'", step.Rule.Replace("Int.inductionOn'", "")));
113+
}
114+
101115
[Fact]
102116
public void WhatWasTriedAndAbandonedIsNotAStep()
103117
{

0 commit comments

Comments
 (0)