Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>
/// <c>b ^ e mod m</c> and <c>n! mod m</c>, for whole numbers <c>b</c>, <c>e &gt;= 0</c>,
/// <c>n &gt;= 0</c> and <c>m</c> not 0, reduced modulo <c>m</c> as they are built, so the
/// power or factorial is never written out: <c>2 ^ (10 ^ 8) mod 1000</c> took 29 s and
/// 13.9 GB, and <c>10 ^ (10 ^ 9) mod 7</c> did not finish in a minute. The remainder is
/// the floored one, as the operator's: <c>|m| | n!</c> once <c>n &gt;= |m|</c>, so that is
/// 0. Null otherwise, and for <c>0 ^ 0</c>, which has no value.
/// https://github.com/asc-community/AngouriMath/pull/2327#issuecomment-6575158568
/// </summary>
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);
}

/// <inheritdoc/>
protected override Entity InnerSimplify(bool isExact) =>
OfALargeWhole(Dividend, Divisor) ??
ExpandOnTwoArguments(Dividend, Divisor,
(a, b) => (a, b) switch
{
Expand Down
69 changes: 69 additions & 0 deletions Sources/Tests/UnitTests/Common/ARemainderOfALargeWholeTest.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// <c>b ^ e mod m</c> and <c>n! mod m</c> for whole numbers, reduced modulo <c>m</c> as they are
/// built. The power or the factorial was written out first: <c>2 ^ (10 ^ 8) mod 1000</c> took
/// 29 s and 13.9 GB, and <c>10 ^ (10 ^ 9) mod 7</c> did not finish.
/// https://github.com/asc-community/AngouriMath/pull/2327#issuecomment-6575158568
/// </summary>
[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");
}
}
}
Loading