Skip to content

Commit 5c725f2

Browse files
Take a remainder of a whole power or factorial as it is built (#2330)
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. #2327 (comment) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8a8ed24 commit 5c725f2

2 files changed

Lines changed: 131 additions & 0 deletions

File tree

‎Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,70 @@ public partial record Modf
280280
// Like division, undefined when the divisor is zero
281281
private protected override Entity IntrinsicCondition => !Divisor.EqualTo(0);
282282

283+
// The largest n for which n! mod m is multiplied out factor by factor, when n < |m|:
284+
// in machine words under 2^31, where 10^7 factors take 0.06 s, and in EInteger above
285+
// it, where they take 1 s and 2.3 GB of short-lived garbage. Past it the factorial is
286+
// built whole, as before.
287+
private const int MaxFactorialMultipliedModulo = 10_000_000;
288+
289+
/// <summary>
290+
/// <c>b ^ e mod m</c> and <c>n! mod m</c>, for whole numbers <c>b</c>, <c>e &gt;= 0</c>,
291+
/// <c>n &gt;= 0</c> and <c>m</c> not 0, reduced modulo <c>m</c> as they are built, so the
292+
/// power or factorial is never written out: <c>2 ^ (10 ^ 8) mod 1000</c> took 29 s and
293+
/// 13.9 GB, and <c>10 ^ (10 ^ 9) mod 7</c> did not finish in a minute. The remainder is
294+
/// the floored one, as the operator's: <c>|m| | n!</c> once <c>n &gt;= |m|</c>, so that is
295+
/// 0. Null otherwise, and for <c>0 ^ 0</c>, which has no value.
296+
/// https://github.com/asc-community/AngouriMath/pull/2327#issuecomment-6575158568
297+
/// </summary>
298+
private static Entity? OfALargeWhole(Entity dividend, Entity divisor)
299+
{
300+
if (dividend is not (Powf or Factorialf) || divisor.Evaled is not Integer { EInteger: var m } || m.IsZero)
301+
return null;
302+
var modulus = m.Abs();
303+
PeterO.Numbers.EInteger? remainder = null;
304+
if (dividend is Powf(var @base, var exponent)
305+
&& @base.Evaled is Integer { EInteger: var b } && exponent.Evaled is Integer { EInteger: var e } && e.Sign >= 0
306+
&& !(b.IsZero && e.IsZero))
307+
{
308+
var reduced = b.Remainder(modulus);
309+
if (reduced.Sign < 0)
310+
reduced += modulus;
311+
remainder = reduced.ModPow(e, modulus).Remainder(modulus);
312+
}
313+
else if (dividend is Factorialf(var argument) && argument.Evaled is Integer { EInteger: var n } && n.Sign >= 0)
314+
{
315+
if (n.CompareTo(modulus) >= 0)
316+
remainder = PeterO.Numbers.EInteger.Zero;
317+
else if (n.CompareTo(PeterO.Numbers.EInteger.FromInt32(MaxFactorialMultipliedModulo)) <= 0)
318+
{
319+
var last = n.ToInt32Checked();
320+
// Under 2^31 the running product times the next factor fits a long.
321+
if (modulus.CanFitInInt32())
322+
{
323+
var small = modulus.ToInt32Checked();
324+
var product = 1L % small;
325+
for (var k = 2; k <= last; k++)
326+
product = product * k % small;
327+
remainder = PeterO.Numbers.EInteger.FromInt64(product);
328+
}
329+
else
330+
{
331+
var product = PeterO.Numbers.EInteger.One.Remainder(modulus);
332+
for (var k = 2; k <= last; k++)
333+
product = (product * k).Remainder(modulus);
334+
remainder = product;
335+
}
336+
}
337+
}
338+
if (remainder is not { } r)
339+
return null;
340+
// Floored: a remainder takes the divisor's sign, so a negative m moves it into (m, 0].
341+
return Integer.Create(m.Sign < 0 && !r.IsZero ? r + m : r);
342+
}
343+
283344
/// <inheritdoc/>
284345
protected override Entity InnerSimplify(bool isExact) =>
346+
OfALargeWhole(Dividend, Divisor) ??
285347
ExpandOnTwoArguments(Dividend, Divisor,
286348
(a, b) => (a, b) switch
287349
{
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
//
2+
// Copyright (c) 2019-2026 Angouri.
3+
// AngouriMath is licensed under MIT.
4+
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
5+
// Website: https://am.angouri.org.
6+
//
7+
8+
using System;
9+
using AngouriMath;
10+
using Xunit;
11+
using static AngouriMath.Entity.Number;
12+
13+
namespace AngouriMath.Tests.Common
14+
{
15+
/// <summary>
16+
/// <c>b ^ e mod m</c> and <c>n! mod m</c> for whole numbers, reduced modulo <c>m</c> as they are
17+
/// built. The power or the factorial was written out first: <c>2 ^ (10 ^ 8) mod 1000</c> took
18+
/// 29 s and 13.9 GB, and <c>10 ^ (10 ^ 9) mod 7</c> did not finish.
19+
/// https://github.com/asc-community/AngouriMath/pull/2327#issuecomment-6575158568
20+
/// </summary>
21+
[Trait("Area", "Common")]
22+
public sealed class ARemainderOfALargeWholeTest
23+
{
24+
// Each expected value is Python's: pow(b, e, m), math.factorial(n) % m, or the product
25+
// reduced as it goes, and the operator's floored remainder takes the divisor's sign.
26+
[Theory]
27+
[InlineData("10 ^ (10 ^ 9) mod 7", 4)]
28+
[InlineData("2 ^ (10 ^ 8) mod 1000", 376)]
29+
[InlineData("(2 ^ 100) ^ (10 ^ 9) mod 1000000007", 25600497)]
30+
[InlineData("(-3) ^ 5 mod 7", 2)]
31+
[InlineData("(-3) ^ 5 mod (-7)", -5)]
32+
[InlineData("3 ^ 5 mod (-7)", -2)]
33+
[InlineData("7 ^ 0 mod 5", 1)]
34+
[InlineData("0 ^ 3 mod 5", 0)]
35+
[InlineData("5 ^ 3 mod 1", 0)]
36+
[InlineData("(10 ^ 5)! mod 1000003", 353746)]
37+
// Wilson: (p - 1)! = -1 mod p, so (p - 3)! = -1/2, which is (p - 1)/2.
38+
[InlineData("(10 ^ 6)! mod 1000003", 500001)]
39+
[InlineData("(10 ^ 7)! mod 1000000007", 682498929)]
40+
[InlineData("(10 ^ 6)! mod (10 ^ 12 + 39)", 981156865440)]
41+
[InlineData("20! mod 7", 0)]
42+
[InlineData("6! mod (-7)", -1)]
43+
[InlineData("0! mod 3", 1)]
44+
public void IsTheRemainder(string expression, long expected)
45+
{
46+
Assert.Equal(Integer.Create(expected), ((Entity)expression).Evaled);
47+
Assert.Equal(Integer.Create(expected), ((Entity)expression).InnerSimplified);
48+
}
49+
50+
// 0 ^ 0 has no value, and a power that is not whole is the remainder it was.
51+
[Fact]
52+
public void ZeroToTheZeroHasNone() => Assert.True(((Entity)"0 ^ 0 mod 5").Evaled.IsNaN);
53+
54+
[Fact]
55+
public void AReciprocalIsNotWhole() => Assert.Equal(Rational.Create(1, 2), ((Entity)"2 ^ (-1) mod 3").Evaled);
56+
57+
// Writing the power out took 772 MB; reduced as it is built it takes under 1 MB. Bytes
58+
// allocated on this thread are what is measured, so tests running beside it do not count.
59+
[Fact]
60+
public void ThePowerIsNotWrittenOut()
61+
{
62+
Entity remainder = "2 ^ (10 ^ 7) mod 1000";
63+
var before = GC.GetAllocatedBytesForCurrentThread();
64+
Assert.Equal(Integer.Create(376), remainder.Evaled);
65+
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
66+
Assert.True(allocated < 20_000_000, $"2 ^ (10 ^ 7) mod 1000 allocated {allocated} bytes");
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)