From d3d8f706649a491cb16ab5d5d028437652b12ff6 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 2 Nov 2026 13:14:33 +0000 Subject: [PATCH] Take a remainder of a whole power or factorial as it is built b ^ e mod m and n! mod m, for whole b, e >= 0, n >= 0 and m not 0, wrote the power or the factorial out first and then divided. They are now reduced modulo m as they are built: the power by modular exponentiation, the factorial factor by factor (in machine words under 2^31), and n! mod m is 0 outright once n >= |m|, since |m| then divides it. The remainder is the floored one, as the operator's. | | before | after | |---|---|---| | 2^(10^8) mod 1000 | 29 s, 13.9 GB | 2 ms, 0.8 MB | | 2^(10^7) mod 1000 | 0.68 s, 772 MB | 44 ms, 0.8 MB | | 10^(10^9) mod 7 | no answer in 60 s | 35 ms | | (10^5)! mod 1000003 | 21 s, 13.7 GB | 4 ms, 0.8 MB | | (10^7)! mod 1000000007 | -- | 62 ms | 0 ^ 0, a negative or symbolic exponent, and a divisor that is not a whole number are left to the evaluation as before. No answer changes; the ones that change are those that never finished. https://github.com/asc-community/AngouriMath/pull/2327#issuecomment-6575158568 Co-Authored-By: Claude Opus 5.5 --- ...aluation.Continuous.Arithmetics.Classes.cs | 62 +++++++++++++++++ .../Common/ARemainderOfALargeWholeTest.cs | 69 +++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 Sources/Tests/UnitTests/Common/ARemainderOfALargeWholeTest.cs diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs index ddc4704eb..198a2e85e 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs @@ -280,8 +280,70 @@ public partial record Modf // Like division, undefined when the divisor is zero private protected override Entity IntrinsicCondition => !Divisor.EqualTo(0); + // The largest n for which n! mod m is multiplied out factor by factor, when n < |m|: + // in machine words under 2^31, where 10^7 factors take 0.06 s, and in EInteger above + // it, where they take 1 s and 2.3 GB of short-lived garbage. Past it the factorial is + // built whole, as before. + private const int MaxFactorialMultipliedModulo = 10_000_000; + + /// + /// b ^ e mod m and n! mod m, for whole numbers b, e >= 0, + /// n >= 0 and m not 0, reduced modulo m as they are built, so the + /// power or factorial is never written out: 2 ^ (10 ^ 8) mod 1000 took 29 s and + /// 13.9 GB, and 10 ^ (10 ^ 9) mod 7 did not finish in a minute. The remainder is + /// the floored one, as the operator's: |m| | n! once n >= |m|, so that is + /// 0. Null otherwise, and for 0 ^ 0, which has no value. + /// https://github.com/asc-community/AngouriMath/pull/2327#issuecomment-6575158568 + /// + private static Entity? OfALargeWhole(Entity dividend, Entity divisor) + { + if (dividend is not (Powf or Factorialf) || divisor.Evaled is not Integer { EInteger: var m } || m.IsZero) + return null; + var modulus = m.Abs(); + PeterO.Numbers.EInteger? remainder = null; + if (dividend is Powf(var @base, var exponent) + && @base.Evaled is Integer { EInteger: var b } && exponent.Evaled is Integer { EInteger: var e } && e.Sign >= 0 + && !(b.IsZero && e.IsZero)) + { + var reduced = b.Remainder(modulus); + if (reduced.Sign < 0) + reduced += modulus; + remainder = reduced.ModPow(e, modulus).Remainder(modulus); + } + else if (dividend is Factorialf(var argument) && argument.Evaled is Integer { EInteger: var n } && n.Sign >= 0) + { + if (n.CompareTo(modulus) >= 0) + remainder = PeterO.Numbers.EInteger.Zero; + else if (n.CompareTo(PeterO.Numbers.EInteger.FromInt32(MaxFactorialMultipliedModulo)) <= 0) + { + var last = n.ToInt32Checked(); + // Under 2^31 the running product times the next factor fits a long. + if (modulus.CanFitInInt32()) + { + var small = modulus.ToInt32Checked(); + var product = 1L % small; + for (var k = 2; k <= last; k++) + product = product * k % small; + remainder = PeterO.Numbers.EInteger.FromInt64(product); + } + else + { + var product = PeterO.Numbers.EInteger.One.Remainder(modulus); + for (var k = 2; k <= last; k++) + product = (product * k).Remainder(modulus); + remainder = product; + } + } + } + if (remainder is not { } r) + return null; + // Floored: a remainder takes the divisor's sign, so a negative m moves it into (m, 0]. + return Integer.Create(m.Sign < 0 && !r.IsZero ? r + m : r); + } + /// protected override Entity InnerSimplify(bool isExact) => + OfALargeWhole(Dividend, Divisor) ?? ExpandOnTwoArguments(Dividend, Divisor, (a, b) => (a, b) switch { diff --git a/Sources/Tests/UnitTests/Common/ARemainderOfALargeWholeTest.cs b/Sources/Tests/UnitTests/Common/ARemainderOfALargeWholeTest.cs new file mode 100644 index 000000000..0727aed60 --- /dev/null +++ b/Sources/Tests/UnitTests/Common/ARemainderOfALargeWholeTest.cs @@ -0,0 +1,69 @@ +// +// 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; +using AngouriMath; +using Xunit; +using static AngouriMath.Entity.Number; + +namespace AngouriMath.Tests.Common +{ + /// + /// b ^ e mod m and n! mod m for whole numbers, reduced modulo m as they are + /// built. The power or the factorial was written out first: 2 ^ (10 ^ 8) mod 1000 took + /// 29 s and 13.9 GB, and 10 ^ (10 ^ 9) mod 7 did not finish. + /// https://github.com/asc-community/AngouriMath/pull/2327#issuecomment-6575158568 + /// + [Trait("Area", "Common")] + public sealed class ARemainderOfALargeWholeTest + { + // Each expected value is Python's: pow(b, e, m), math.factorial(n) % m, or the product + // reduced as it goes, and the operator's floored remainder takes the divisor's sign. + [Theory] + [InlineData("10 ^ (10 ^ 9) mod 7", 4)] + [InlineData("2 ^ (10 ^ 8) mod 1000", 376)] + [InlineData("(2 ^ 100) ^ (10 ^ 9) mod 1000000007", 25600497)] + [InlineData("(-3) ^ 5 mod 7", 2)] + [InlineData("(-3) ^ 5 mod (-7)", -5)] + [InlineData("3 ^ 5 mod (-7)", -2)] + [InlineData("7 ^ 0 mod 5", 1)] + [InlineData("0 ^ 3 mod 5", 0)] + [InlineData("5 ^ 3 mod 1", 0)] + [InlineData("(10 ^ 5)! mod 1000003", 353746)] + // Wilson: (p - 1)! = -1 mod p, so (p - 3)! = -1/2, which is (p - 1)/2. + [InlineData("(10 ^ 6)! mod 1000003", 500001)] + [InlineData("(10 ^ 7)! mod 1000000007", 682498929)] + [InlineData("(10 ^ 6)! mod (10 ^ 12 + 39)", 981156865440)] + [InlineData("20! mod 7", 0)] + [InlineData("6! mod (-7)", -1)] + [InlineData("0! mod 3", 1)] + public void IsTheRemainder(string expression, long expected) + { + Assert.Equal(Integer.Create(expected), ((Entity)expression).Evaled); + Assert.Equal(Integer.Create(expected), ((Entity)expression).InnerSimplified); + } + + // 0 ^ 0 has no value, and a power that is not whole is the remainder it was. + [Fact] + public void ZeroToTheZeroHasNone() => Assert.True(((Entity)"0 ^ 0 mod 5").Evaled.IsNaN); + + [Fact] + public void AReciprocalIsNotWhole() => Assert.Equal(Rational.Create(1, 2), ((Entity)"2 ^ (-1) mod 3").Evaled); + + // Writing the power out took 772 MB; reduced as it is built it takes under 1 MB. Bytes + // allocated on this thread are what is measured, so tests running beside it do not count. + [Fact] + public void ThePowerIsNotWrittenOut() + { + Entity remainder = "2 ^ (10 ^ 7) mod 1000"; + var before = GC.GetAllocatedBytesForCurrentThread(); + Assert.Equal(Integer.Create(376), remainder.Evaled); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.True(allocated < 20_000_000, $"2 ^ (10 ^ 7) mod 1000 allocated {allocated} bytes"); + } + } +}