From 53635e679982d2e1c80a605c1b62c0b7181aa3d8 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 21 Sep 2026 09:10:32 +0000 Subject: [PATCH 1/2] n in ZZ and 2^n > n^2 is solved to a set: a window searched and its tails proved by induction An inequality with an exponential or a factorial over the whole numbers, conjoined with the membership, is searched over a window from the least member; the members are the points where it holds, and the whole numbers from the start of the final run -- and over ZZ down from the end of the first -- where the quantifier proves the statement there by induction. A tail it does not prove leaves the inequality solver's refusal in place: a window is evidence about the window. Sullivan and Mackey's Ex 5.3.2 is { 0, 1 } \/ ZZ /\ [5; +oo). The inequality induction reads the sign of the whole expression off its shape before looking for a step, which is what proves a downward tail. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura --- BREAKING-CHANGES.md | 15 +++ Sources/.editorconfig | 6 ++ Sources/AngouriMath/Docs/Usage/Syntax.md | 6 +- .../Functions/Boolean/Quantifiers.cs | 7 +- .../Solvers/EquationSolver/SolveStatement.cs | 6 ++ .../InequalitySolver/ThresholdSearch.cs | 101 ++++++++++++++++++ .../UnitTests/Algebra/ThresholdSetTest.cs | 64 +++++++++++ 7 files changed, 202 insertions(+), 3 deletions(-) create mode 100644 Sources/AngouriMath/Functions/Continuous/Solvers/InequalitySolver/ThresholdSearch.cs create mode 100644 Sources/Tests/UnitTests/Algebra/ThresholdSetTest.cs diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index f29d8c30a..e845569c4 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -788,6 +788,21 @@ written | `"forall n in ZZ+ : n! >= 2^(n - 1)".ToEntity().Evaled` | `UnhandledParseException` | `True` | | `"forall n in ZZ+ /\\ [4; +oo) : n^2 - 2 n - 1 > 0".ToEntity().Evaled` | `UnhandledParseException` | `True` — decided about `4 + t` over `ZZ*` | +### `n in ZZ and 2^n > n^2` is solved to a set, and was a refusal + +An inequality with an exponential or a factorial over the whole numbers is solved to the members +of a window from the least member and the rays the quantifier proves by induction, upwards and, +over `ZZ`, downwards; a tail it does not prove leaves the refusal in place, since a window is +evidence about the window ([#1409](https://github.com/asc-community/AngouriMath/issues/1409), +Sullivan and Mackey's Ex 5.3.2 and Prob 5.7.2, 5.7.8–9). + +| Input | Was (2.5.0) | Now | +|---|---|---| +| `"n in ZZ and 2^n > n^2".ToEntity().Solve("n")` | `NotSufficientlySupportedException` — "Only polynomial inequalities are supported" | `{ 0, 1 } \/ ZZ /\ [5; +oo)` | +| `"n in ZZ+ and n! > 3^n".ToEntity().Solve("n")` | `NotSufficientlySupportedException` | `ZZ+ /\ [7; +oo)` | +| `"n in ZZ and n^3 < 3^(n - 1)".ToEntity().Solve("n")` | `NotSufficientlySupportedException` | `ZZ /\ (-oo; 0] \/ ZZ /\ [6; +oo)` | +| `"n in ZZ and 2^n >= n^2 - 3 n + 3".ToEntity().Solve("n")` | `NotSufficientlySupportedException` | the same — the tail from `1` is not proved, and the window is not guessed from | + ### `binomial(n, k)` is a function **Addition, not silent.** The binomial coefficient is a node, `Entity.Binomialf`, spelled diff --git a/Sources/.editorconfig b/Sources/.editorconfig index 8a2013edd..da4813c90 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -291,6 +291,12 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [AngouriMath/Functions/NumberTheory/ResidueClasses.cs] file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n +[AngouriMath/Functions/Continuous/Solvers/InequalitySolver/ThresholdSearch.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[Tests/UnitTests/Algebra/ThresholdSetTest.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + [Tests/UnitTests/Core/InductionTest.cs] file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n diff --git a/Sources/AngouriMath/Docs/Usage/Syntax.md b/Sources/AngouriMath/Docs/Usage/Syntax.md index 35f9e47e6..3ca70f21b 100644 --- a/Sources/AngouriMath/Docs/Usage/Syntax.md +++ b/Sources/AngouriMath/Docs/Usage/Syntax.md @@ -85,7 +85,11 @@ congruence is solved to a residue class — `"3 x = 11 (mod 7)".ToEntity().Solve Chinese remainder theorem, `x = 3 (mod 4) and x = 5 (mod 6)` giving `{ x in ZZ : x = 11 (mod 12) }` and `x = 3 (mod 4) and x = 2 (mod 6)` nothing, and with a bounded interval the members are listed: `x = 2 (mod 7) and 0 <= x and x < 30` is `{ 2, 9, 16, 23 }`. `MathS.NumberTheory.ModularInverse(3, 10)` -is `7`, the one representative in `[1, n - 1]`, and `null` where `a` and `n` share a factor. +is `7`, the one representative in `[1, n - 1]`, and `null` where `a` and `n` share a factor. An +inequality with an exponential or a factorial over the whole numbers, `n in ZZ and 2^n > n^2`, is +solved to the members of a window from the least member and the tails the quantifier proves by +induction — `{ 0, 1 } \/ ZZ /\ [5; +oo)`, `n in ZZ+ and n! > 3^n` is `ZZ+ /\ [7; +oo)` — and where +a tail is not proved the window is not an answer, and the inequality solver refuses as before. | 9 | `unite` `\/`, `setsubtract` `\` | one level, so `A \/ B \ C` is `(A \/ B) \ C` | | 10 | `intersect` `/\` | | | 11 | `+` `-` | | diff --git a/Sources/AngouriMath/Functions/Boolean/Quantifiers.cs b/Sources/AngouriMath/Functions/Boolean/Quantifiers.cs index bead63058..cac9a759c 100644 --- a/Sources/AngouriMath/Functions/Boolean/Quantifiers.cs +++ b/Sources/AngouriMath/Functions/Boolean/Quantifiers.cs @@ -156,7 +156,7 @@ internal enum Kind { All, Some, Unique } /// The least member of a set of whole numbers bounded below -- ZZ+, ZZ*, /// either cut by an interval -- or where the set is something else. /// - private static Integer? LeastMember(Set set) + internal static Integer? LeastMember(Set set) { switch (set) { @@ -282,6 +282,9 @@ private static bool IsUnboundedAbove(Intersectionf cut) return Entity.Boolean.False; if (atLeast != Entity.Boolean.True) return null; + // Read off the shape first: 3^(-t - 1) + t^3 is positive on ZZ* term by term. + if (Sign(positive, x, set, isExact) is { } direct && (!strict || direct == Signum.Positive)) + return Entity.Boolean.True; var next = positive.Substitute(x, x + Integer.One); foreach (var c in Multipliers(positive, x)) { @@ -448,7 +451,7 @@ private enum Signum { Positive, NonNegative } _ => null, }; - private static bool IsIntegerSet(SpecialSet set) + internal static bool IsIntegerSet(SpecialSet set) => set.ToDomain() is Domain.Integer or Domain.NonNegativeInteger or Domain.PositiveInteger; /// How many residues a periodic statement is checked over before it is left as written. diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs index 59590193a..9952223c5 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs @@ -332,6 +332,12 @@ internal static Set Solve(Entity expr, Variable x) Equalsf => Empty, + // x in ZZ and an inequality with an exponential or a factorial in x: a window + // searched and its tails proved by induction, so that { n in ZZ : 2^n > n^2 } + // is {0, 1} \/ ZZ /\ [5; +oo) rather than a refusal from the inequality solver. + // https://github.com/asc-community/AngouriMath/issues/1409 + Andf(Inf(var name, Set integers), ComparisonSign inequality) when name == x && ThresholdSearch.Solve(x, integers, inequality) is { } thresholds => thresholds, + Andf(ComparisonSign inequality, Inf(var name, Set integers)) when name == x && ThresholdSearch.Solve(x, integers, inequality) is { } thresholds => thresholds, Andf(var left, var right) => Conjunction(Solve(left, x), Solve(right, x), expr, x), Orf(var left, var right) => diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/InequalitySolver/ThresholdSearch.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/InequalitySolver/ThresholdSearch.cs new file mode 100644 index 000000000..396e0486b --- /dev/null +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/InequalitySolver/ThresholdSearch.cs @@ -0,0 +1,101 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System.Collections.Generic; +using System.Linq; +using AngouriMath.Functions.Boolean; +using static AngouriMath.Entity; +using static AngouriMath.Entity.Number; +using static AngouriMath.Entity.Set; + +namespace AngouriMath.Functions.Algebra.AnalyticalSolving +{ + /// + /// { n in ZZ : 2^n > n^2 }, an inequality with an exponential or a factorial over + /// the whole numbers, is searched over a window from the least member and its tails are + /// proved: the members are the points of the window where it holds, and the whole numbers + /// from the start of the final run where the quantifier decides it holds there -- by + /// induction, which is how Sullivan and Mackey do it (Ex 5.3.2: {0, 1} \/ ZZ /\ [5; +oo)). + /// Over ZZ the other tail is proved the same way, downwards. A tail the quantifier + /// leaves undecided leaves the set as written: a window is evidence about the window. + /// https://github.com/asc-community/AngouriMath/issues/1409 + /// + internal static class ThresholdSearch + { + /// How far from the least member, or from zero, the window reaches. + private const int Window = 64; + + internal static Set? Solve(Variable x, Set integers, ComparisonSign inequality) + { + if (inequality is Equalsf || inequality.Vars.Any(v => v != x)) + return null; + if (!inequality.Nodes.Any(node => node is Powf(_, var e) && e.ContainsNode(x) || node is Factorialf f && f.ContainsNode(x))) + return null; + if (integers is not SpecialSet special || !Quantifiers.IsIntegerSet(special)) + return null; + var least = Quantifiers.LeastMember(special); + var from = least is null ? -Window : least.EInteger.ToInt32Checked(); + var truth = new List(); + for (var n = from; n <= Window; n++) + { + if (inequality.Substitute(x, Integer.Create(n)).Evaled is not Entity.Boolean(var holds)) + return null; + truth.Add(holds); + } + // The final run, and the first one over ZZ, are what the quantifier is asked about. + var last = truth.Count - 1; + var tailStart = last; + while (tailStart > 0 && truth[tailStart - 1] == truth[last]) + tailStart--; + var upwards = truth[last] ? inequality : Negated(inequality); + if (!Holds(upwards, x, from + tailStart, downwards: false)) + return null; + var headEnd = 0; + if (least is null) + { + while (headEnd < tailStart - 1 && truth[headEnd + 1] == truth[0]) + headEnd++; + if (!Holds(truth[0] ? inequality : Negated(inequality), x, from + headEnd, downwards: true)) + return null; + } + // One run over the whole window, proved on every side, is the whole set. + if (tailStart == 0 && truth[last]) + return special; + if (tailStart == 0) + return Empty; + var listed = new List(); + for (var i = least is null ? headEnd + 1 : 0; i < tailStart; i++) + if (truth[i]) + listed.Add(Integer.Create(from + i)); + Set result = new FiniteSet(listed); + if (least is null && truth[0]) + result = result.Unite(special.Intersect(new Interval(Real.NegativeInfinity, false, Integer.Create(from + headEnd), true))); + if (truth[last]) + result = result.Unite(special.Intersect(new Interval(Integer.Create(from + tailStart), true, Real.PositiveInfinity, false))); + return result; + } + + /// Whether the statement holds at every whole number from on, or down from it. + private static bool Holds(Entity statement, Variable x, int start, bool downwards) + { + var t = Variable.CreateUnique(statement, "t"); + Entity shifted = downwards ? Integer.Create(start) - t : Integer.Create(start) + t; + var body = statement.Substitute(x, shifted).InnerSimplified; + return Quantifiers.Decide(Quantifiers.Kind.All, t, MathS.Sets.NonNegativeIntegers, body, true) is Entity.Boolean(true); + } + + private static ComparisonSign Negated(ComparisonSign inequality) + => inequality switch + { + Greaterf(var a, var b) => new LessOrEqualf(a, b), + GreaterOrEqualf(var a, var b) => new Lessf(a, b), + Lessf(var a, var b) => new GreaterOrEqualf(a, b), + LessOrEqualf(var a, var b) => new Greaterf(a, b), + _ => throw new Core.Exceptions.AngouriBugException("An equation is refused above"), + }; + } +} diff --git a/Sources/Tests/UnitTests/Algebra/ThresholdSetTest.cs b/Sources/Tests/UnitTests/Algebra/ThresholdSetTest.cs new file mode 100644 index 000000000..20b8fd0ba --- /dev/null +++ b/Sources/Tests/UnitTests/Algebra/ThresholdSetTest.cs @@ -0,0 +1,64 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System.Linq; +using AngouriMath; +using AngouriMath.Extensions; +using Xunit; +using static AngouriMath.Entity; + +namespace AngouriMath.Tests.Algebra +{ + /// + /// n in ZZ and 2^n > n^2 solved as a set: a window from the least member searched, the + /// members listed, and the tails proved by the quantifier's induction -- so the answer is a + /// finite set and rays of whole numbers, never a guess from the window. Sullivan and Mackey's + /// Ex 5.3.2, §5.3.4 Try 4, Prob 5.7.2 and 5.7.8-9, with the thresholds the book derives. + /// + /// + [Trait("Area", "Algebra")] + public sealed class ThresholdSetTest + { + [Theory] + // Ex 5.3.2: 2^n > n^2 exactly on {0, 1} and from 5. + [InlineData("n in ZZ and 2^n > n^2", "{0, 1} \\/ (ZZ /\\ [5; +oo))")] + [InlineData("n in ZZ+ and 2^n > n^2", "{1} \\/ (ZZ+ /\\ [5; +oo))")] + // §5.3.4 Try 4: n^3 < 3^(n - 1) holds for n <= 0 and from 6. + [InlineData("n in ZZ and n^3 < 3^(n - 1)", "(ZZ /\\ (-oo; 0]) \\/ (ZZ /\\ [6; +oo))")] + // Prob 5.7.2: 3^n > n^4 at 1 and from 8; 4^n > n^4 at 1 and from 5. + [InlineData("n in ZZ+ and 3^n > n^4", "{1} \\/ (ZZ+ /\\ [8; +oo))")] + [InlineData("n in ZZ+ and 4^n > n^4", "{1} \\/ (ZZ+ /\\ [5; +oo))")] + // Prob 5.7.8-9: n! > 2^n from 4, n! > 3^n from 7, n! > 5^n from 12. + [InlineData("n in ZZ+ and n! > 2^n", "ZZ+ /\\ [4; +oo)")] + [InlineData("n in ZZ+ and n! > 3^n", "ZZ+ /\\ [7; +oo)")] + [InlineData("n in ZZ+ and n! > 5^n", "ZZ+ /\\ [12; +oo)")] + // The inequality on either side of the conjunction, and the other comparisons. + [InlineData("3^n < n! and n in ZZ+", "ZZ+ /\\ [7; +oo)")] + [InlineData("n in ZZ+ and 2^n <= n^2", "{2, 3, 4}")] + [InlineData("n in ZZ+ and 2^n >= n^2", "{1, 2} \\/ (ZZ+ /\\ [4; +oo))")] + // One run over the whole window is the whole set, or none of it. + [InlineData("n in ZZ* and 2^n >= n + 1", "ZZ*")] + [InlineData("n in ZZ+ and 2^n < n", "{}")] + [InlineData("n in ZZ and 2^n < 0", "{}")] + public void TheMembersAreListedAndTheTailsProved(string statement, string expected) + { + var solved = statement.ToEntity().Solve("n"); + var wanted = expected.ToEntity().Evaled; + // The same set two ways is the same set: compared by membership at the points a + // threshold could be wrong at, rather than by the printed union. + foreach (var at in Enumerable.Range(-20, 41)) + Assert.Equal(MathS.Sets.ElementInSet(at, (Set)wanted).Evaled, MathS.Sets.ElementInSet(at, solved).Evaled); + } + + [Theory] + // A tail the induction does not prove leaves the statement to the inequality solver, + // which refuses an exponential: a window is evidence about the window only. + [InlineData("n in ZZ and 2^n >= n^2 - 3 n + 3")] + public void AnUnprovedTailIsNotGuessed(string statement) + => Assert.ThrowsAny(() => statement.ToEntity().Solve("n")); + } +} From cb3f9ab8ddac21183a01adfe202ac89b6b243457 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 21 Sep 2026 09:35:14 +0000 Subject: [PATCH 2/2] A power of a whole base repeats modulo m with the base's order, so the residues decide it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit forall n in ZZ+ : 3 divides 7^n - 4^n is one residue and forall n in ZZ* : not (7 divides 2^n + 1) three: a divisibility or a congruence in a polynomial of n and of powers a^e(n), a prime to the modulus and e a whole polynomial, has period lcm(m, ord_m(a), ...) in n over the non-negative whole numbers. A base sharing a factor with the modulus repeats only eventually, and over ZZ a power is fractional at a negative exponent; both are left as written. Sullivan and Mackey's §5.2.4 Try 3 and Ex 5.3.7. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura --- BREAKING-CHANGES.md | 13 +++++ Sources/AngouriMath/Docs/Usage/Syntax.md | 8 ++- .../Functions/Boolean/Quantifiers.cs | 54 ++++++++++++++++--- .../Tests/UnitTests/Core/ResidueClassTest.cs | 20 +++++++ 4 files changed, 87 insertions(+), 8 deletions(-) diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index e845569c4..468c17578 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -803,6 +803,19 @@ Sullivan and Mackey's Ex 5.3.2 and Prob 5.7.2, 5.7.8–9). | `"n in ZZ and n^3 < 3^(n - 1)".ToEntity().Solve("n")` | `NotSufficientlySupportedException` | `ZZ /\ (-oo; 0] \/ ZZ /\ [6; +oo)` | | `"n in ZZ and 2^n >= n^2 - 3 n + 3".ToEntity().Solve("n")` | `NotSufficientlySupportedException` | the same — the tail from `1` is not proved, and the window is not guessed from | +And a divisibility or a congruence with a power of a whole base in the quantified name is decided +by its residues too, over the non-negative whole numbers: `a^n` modulo `m` repeats with the order +of `a` where `a` is prime to `m`, so `forall n in ZZ+ : 3 divides 7^n - 4^n` is `True` by one +residue and `forall n in ZZ* : not (7 divides 2^n + 1)` by three (Sullivan and Mackey's §5.2.4 Try 3 +and Ex 5.3.7). A base sharing a factor with the modulus, or a negative exponent over `ZZ`, is left +as written. + +| Input | Was (2.5.0) | Now | +|---|---|---| +| `forall n in ZZ+ : 3 divides 7^n - 4^n` | `UnhandledParseException` | `True` | +| `forall n in ZZ* : not (7 divides 2^n + 1)` | `UnhandledParseException` | `True` | +| `forall n in ZZ+ : 5 divides 7^n - 1` | `UnhandledParseException` | `False` | + ### `binomial(n, k)` is a function **Addition, not silent.** The binomial coefficient is a node, `Entity.Binomialf`, spelled diff --git a/Sources/AngouriMath/Docs/Usage/Syntax.md b/Sources/AngouriMath/Docs/Usage/Syntax.md index 3ca70f21b..6716823e7 100644 --- a/Sources/AngouriMath/Docs/Usage/Syntax.md +++ b/Sources/AngouriMath/Docs/Usage/Syntax.md @@ -321,7 +321,13 @@ factorial, a polynomial in `n` decided over the set, sums and products of these ZZ+ /\ [5; +oo) : 2^n > n^2` is `True` (`2^(n + 1) - 2 · 2^n` leaves `n^2 - 2 n - 1`, positive from `5`), `forall n in ZZ+ /\ [4; +oo) : 2^n > n^2` is `False` at `4`, and `forall n in ZZ+ : n! >= 2^(n - 1)` is `True`. The whole numbers from `m` are `ZZ*` shifted by `m`, so a statement -over `ZZ+ /\ [4; +oo)` is decided as one about `4 + t` over `ZZ*`, whichever route reads it. `not` +over `ZZ+ /\ [4; +oo)` is decided as one about `4 + t` over `ZZ*`, whichever route reads it. A +divisibility or a congruence in a polynomial of `n` with whole coefficients repeats with the +modulus, so its residues decide it (`forall n in ZZ : 6 divides n^3 + 5 n` is `True` by six cases), +and with a power `a^n` of a whole base prime to the modulus among the terms it repeats with the +order of `a` as well: `forall n in ZZ+ : 3 divides 7^n - 4^n` is `True` by one residue, `forall n +in ZZ* : not (7 divides 2^n + 1)` by three — over the non-negative whole numbers, where the powers +are whole; a base sharing a factor with the modulus repeats only eventually and is left as written. `not` passes through a quantifier by flipping it: `not forall x in S : P` is `exists x in S : not P`. In LaTeX, `\forall x \in S : P`. `forall`, `exists` and `exists!` are keywords, so they are not names. diff --git a/Sources/AngouriMath/Functions/Boolean/Quantifiers.cs b/Sources/AngouriMath/Functions/Boolean/Quantifiers.cs index cac9a759c..c65390987 100644 --- a/Sources/AngouriMath/Functions/Boolean/Quantifiers.cs +++ b/Sources/AngouriMath/Functions/Boolean/Quantifiers.cs @@ -128,7 +128,7 @@ internal enum Kind { All, Some, Unique } // whole coefficients repeats with the modulus, so the residues decide it: // forall n in ZZ : 6 divides n^3 + 5 n is six cases. Sullivan and Mackey's "case // analysis over the classes" (Ex 6.5.14). - if (Period(body, x) is { } period && period.CompareTo(EInteger.FromInt32(LargestPeriod)) <= 0) + if (Period(body, x, integers) is { } period && period.CompareTo(EInteger.FromInt32(LargestPeriod)) <= 0) return OverResidues(kind, x, integers, body, period, isExact); // A polynomial equation with no solution modulo some m has none in the whole // numbers: 3 x^2 - 5 y^2 = 1 is impossible modulo 5 (Ex 6.5.27). Only a refusal @@ -463,27 +463,27 @@ internal static bool IsIntegerSet(SpecialSet set) /// with whole coefficients, joined by the connectives; the least common multiple of the /// parts' periods. /// - private static EInteger? Period(Entity body, Variable x) + private static EInteger? Period(Entity body, Variable x, SpecialSet set) { switch (body) { case Entity.Boolean: return EInteger.One; case Dividesf(Integer divisor, var dividend): - return divisor.EInteger.IsZero || !IsWholePolynomial(dividend) ? null : divisor.EInteger.Abs(); + return divisor.EInteger.IsZero ? null : PeriodModulo(dividend, divisor.EInteger.Abs(), x, set); case Congruentf(var left, var right, Integer modulus): - return modulus.EInteger.IsZero || !IsWholePolynomial(left) || !IsWholePolynomial(right) ? null : modulus.EInteger.Abs(); + return modulus.EInteger.IsZero ? null : PeriodModulo(left - right, modulus.EInteger.Abs(), x, set); case Notf(var operand): - return Period(operand, x); + return Period(operand, x, set); // A quantifier over whole numbers inside: its body is periodic in x with the // same period whatever the inner name takes, so the residues of x decide the // outer statement and the inner one is decided at each of them. case Quantifier { Over: SpecialSet inner } quantifier when IsIntegerSet(inner): - return Period(quantifier.Body, x); + return Period(quantifier.Body, x, set); case Andf or Orf or Impliesf or Xorf: if (body is not IBinaryNode { NodeFirstChild: var first, NodeSecondChild: var second }) return null; - if (Period(first, x) is not { } one || Period(second, x) is not { } another) + if (Period(first, x, set) is not { } one || Period(second, x, set) is not { } another) return null; return one * another / one.Gcd(another); default: @@ -491,6 +491,46 @@ internal static bool IsIntegerSet(SpecialSet set) } } + /// + /// The period, in , of an expression's residue modulo + /// : the modulus for a polynomial with whole coefficients, + /// and with a power a^e of a whole base coprime to the modulus among the terms -- + /// 7^n - 4^n modulo 3, 2^n + 1 modulo 7 -- the least common + /// multiple with the order of each base, since a^(e + k) = a^e modulo m + /// where a^k = 1. Over the non-negative whole numbers only, where the powers are + /// whole; for a base sharing a factor with the modulus, whose + /// powers repeat only eventually. Sullivan and Mackey's Ex 5.3.7 and §5.2.4 Try 3. + /// + private static EInteger? PeriodModulo(Entity expr, EInteger modulus, Variable x, SpecialSet set) + { + if (IsWholePolynomial(expr)) + return modulus; + if (set.ToDomain() is not (Domain.NonNegativeInteger or Domain.PositiveInteger)) + return null; + var period = modulus; + var replaced = expr; + var count = 0; + foreach (var power in expr.Nodes.OfType().Where(p => p.Exponent.ContainsNode(x)).Distinct()) + { + if (power.Base.Evaled is not Integer { EInteger: var @base } || !power.Exponent.Vars.All(v => v == x) || !IsWholePolynomial(power.Exponent)) + return null; + if (!@base.Gcd(modulus).Equals(EInteger.One)) + return null; + var order = EInteger.One; + var value = @base.Mod(modulus); + while (!value.Equals(EInteger.One) && order.CompareTo(modulus) < 0) + { + value = value * @base % modulus; + order += 1; + } + if (!value.Equals(EInteger.One)) + return null; + period = period * order / period.Gcd(order); + replaced = replaced.Substitute(power, Variable.CreateUnique(expr, "power_" + count++)); + } + return IsWholePolynomial(replaced) ? period : null; + } + /// /// A polynomial with whole coefficients in whatever names it mentions -- which is /// periodic in each of them modulo anything, as long as the others stand for whole diff --git a/Sources/Tests/UnitTests/Core/ResidueClassTest.cs b/Sources/Tests/UnitTests/Core/ResidueClassTest.cs index 05b6bf495..bf85fc1eb 100644 --- a/Sources/Tests/UnitTests/Core/ResidueClassTest.cs +++ b/Sources/Tests/UnitTests/Core/ResidueClassTest.cs @@ -108,9 +108,29 @@ public void TheInversesModuloAPrimeAreAPermutation() [InlineData("exists x, y in ZZ : x^2 + y^2 = 5", "True")] // Example 6.5.12: the order of 5 modulo 7 is 6. [InlineData("exists n in ZZ+ : 5^n = 1 (mod 7)", "True")] + // A power of a base prime to the modulus repeats with the base's order, so the residues + // of the exponent decide it: §5.2.4 Try 3, Example 5.3.7 (2^n + 1 modulo 7 is 2, 3 or 5 + // by n modulo 3), and the powers of 7 modulo 6 and 5. + [InlineData("forall n in ZZ+ : 3 divides 7^n - 4^n", "True")] + [InlineData("forall n in ZZ* : not (7 divides 2^n + 1)", "True")] + [InlineData("forall n in ZZ* : 2^n + 1 = 3 (mod 7) or 2^n + 1 = 5 (mod 7) or 2^n + 1 = 2 (mod 7)", "True")] + [InlineData("forall n in ZZ+ : 6 divides 7^n - 1", "True")] + [InlineData("forall n in ZZ+ : 5 divides 7^n - 1", "False")] + [InlineData("exists n in ZZ+ : 5 divides 7^n - 1", "True")] + [InlineData("forall n in ZZ* : 8 divides 3^(2 n) - 1", "True")] + [InlineData("forall n in ZZ+ : 9 divides 4^n + 15 n - 1", "True")] + [InlineData("forall n in ZZ+ : 3 divides 2^n", "False")] public void AQuantifiedStatementIsDecidedByResidues(string statement, string expected) => Assert.Equal(expected.ToEntity(), statement.ToEntity().Simplify()); + [Theory] + // Over ZZ a power has a fractional value at a negative exponent, and a base sharing a + // factor with the modulus repeats only eventually: neither is decided by residues. + [InlineData("forall n in ZZ : 3 divides 7^n - 4^n")] + [InlineData("forall n in ZZ+ /\\ [2; +oo) : 4 divides 2^n")] + public void APowerIsLeftAsWrittenWhereItsResiduesDoNotRepeat(string statement) + => Assert.IsType(statement.ToEntity().Simplify()); + [Theory] // Examples 6.5.15-6.5.17: the quadratic residues modulo 3..8 and the cubic ones modulo 7, 9. [InlineData("({0, 1, 2})^2 mod 3", "{ 0, 1 }")]