Skip to content

Commit ba63f2f

Browse files
Factorise past the longs, and decide IsPrime by Miller-Rabin (#2352)
Factorize, CountDivisors and phi trial-divided over long, and IsPrime was whether the divisor count was 2. Past 2^63 each threw OverflowException, though the first division finds a factor like 2 or 7 at any size, and Simplify folded phi(7^30) to an integer and threw. The loop ran while the divisor's square was at most the running totient, not what was left to factor, so 2^62 took 1.5e9 divisions after the first had divided every 2 out; and past 3037000499 the square wrapped negative, so the largest prime below 2^63 never finished. 2.6.0 does all of this. TryFactorize divides in EInteger as far as 65536, bounded by what is left, asks Primes.IsPrime (Miller-Rabin and Lucas-Lehmer) of the rest, and splits a composite rest by Pollard's rho. phi, the divisor count and Factorize are built on it; where a factor is neither proven prime nor split they throw NotSufficientlySupportedException, and phi(n) in an expression is left as written. IsPrime is Primes.IsPrime, throwing where primality is not decided, and the two phi(p^k) rules fire only where it is proven. The compiled totient, over double and long, takes the same path: its loop wrapped the same way. Closes #2341 Closes #2342 Write the compiled totient's long and int overloads in the template MathAllMethods.cs is generated from MathAllMethods.tt, and the Regenerate job rebuilt it with the long overload calling the long Phi this branch removed. The template now writes what the generated file already has. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 339204f commit ba63f2f

11 files changed

Lines changed: 242 additions & 78 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,23 @@ arcsine of that is `NaN`. Of `arcsin(k + c)` for `k` from 1 to 40 and `c` in `pi
506506
| `"arcsin(6 + pi)".ToEntity().Evaled` | `NaN` | `1.5707963267948966 - 2.902976737696685i`, to 15 digits |
507507
| `"arccos(6 + pi)".ToEntity().Evaled` | `NaN` | `2.902976737696685i`, to 15 digits |
508508

509+
### Factorisation, the divisor count, the totient and `IsPrime` answer past 2^63
510+
511+
**Not silent: what threw or did not return now answers.** The three trial-divided over `long`, and `IsPrime` was
512+
whether the divisor count was 2: past 2^63 each threw `OverflowException`, `phi(7^30)` out of `Simplify` among them,
513+
and the largest prime below 2^63 did not finish. They divide in `EInteger` now, as far as 65536, and ask
514+
Miller–Rabin and Lucas–Lehmer of what is left, splitting a composite rest by Pollard's rho. Where a factor is neither
515+
proven prime nor split, `Factorize`, `CountDivisors`, `Phi` and `IsPrime` throw `NotSufficientlySupportedException`,
516+
and `phi(n)` in an expression is left as written. https://github.com/asc-community/AngouriMath/issues/2341,
517+
https://github.com/asc-community/AngouriMath/issues/2342
518+
519+
| Input | Was (2.6.0) | Now |
520+
|---|---|---|
521+
| `MathS.NumberTheory.Factorize(2^64)` | `OverflowException` | `(2, 64)` |
522+
| `"phi(7^30)".Simplify()` | `OverflowException` | `19319434534879078361025642` |
523+
| `(2^89 - 1).IsPrime` | `OverflowException` | `true` |
524+
| `MathS.NumberTheory.Factorize(9223372036854775783)` | does not return | `(9223372036854775783, 1)` |
525+
509526
### An exact rational is zero, positive or negative as it is
510527

511528
**Silent: 0 divided by a rational smaller than about 1e-199 is 0, where it was NaN.** Whether an exact rational was zero,

‎Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Integer.Definition.cs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,16 @@ public static Integer Create(EInteger value)
8989
/// <summary>
9090
/// Detemine whether integer is prime or not.
9191
/// </summary>
92-
public bool IsPrime => CountDivisors() == 2;
92+
/// <remarks>
93+
/// By Miller–Rabin and Lucas–Lehmer, as membership in <c>PP</c> is. It was whether the number had two
94+
/// divisors, by trial division over <c>long</c>, so <c>2^89 - 1</c> threw <c>OverflowException</c> and the
95+
/// largest prime below 2^63 did not finish. Where primality is not decided -- past
96+
/// <c>3317044064679887385961981</c>, for a number that is not a Mersenne number and passes every test --
97+
/// it throws <see cref="Core.Exceptions.NotSufficientlySupportedException"/>.
98+
/// https://github.com/asc-community/AngouriMath/issues/2341
99+
/// </remarks>
100+
public bool IsPrime => Functions.Primes.IsPrime(EInteger)
101+
?? throw new Core.Exceptions.NotSufficientlySupportedException($"Whether {EInteger} is prime is not decided");
93102

94103
/// <summary>
95104
/// Deconstructs as record

‎Sources/AngouriMath/Core/Transformations/Matching/MatchedRules.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,7 @@ internal static class MatchedRules
584584
"eulers-totient-of-a-prime-power",
585585
MatchPattern.Node<Phif>(
586586
MatchPattern.Node<Powf>(
587-
MatchPattern.Any<Integer>("p", p => p.IsPrime),
587+
MatchPattern.Any<Integer>("p", p => Functions.Primes.IsPrime(p.EInteger) is true),
588588
MatchPattern.Any("k"))),
589589
// (Integer) on the prime and not on the exponent, and the difference is the
590590
// point: p - 1 is arithmetic that folds to a number, k - 1 is a tree because k

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -425,9 +425,9 @@ private static IEnumerable<EInteger> Divisors(EInteger n)
425425
{
426426
var extended = new List<EInteger>(divisors);
427427
var multiplier = EInteger.One;
428-
for (long i = 0; i < power; i++)
428+
for (var i = EInteger.Zero; i < power; i += 1)
429429
{
430-
multiplier = multiplier.Multiply(EInteger.FromInt64(prime));
430+
multiplier = multiplier.Multiply(prime);
431431
foreach (var divisor in divisors)
432432
extended.Add(divisor.Multiply(multiplier));
433433
}

‎Sources/AngouriMath/Functions/Compilation/IntoLinq/MathAllMethods.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -306,8 +306,8 @@ public static System.Numerics.Complex Round(System.Numerics.Complex a)
306306
public static System.Numerics.Complex Phi(System.Numerics.Complex a) => AngouriMath.Numerics.SpecialFunctions.Phi(a);
307307
public static double Phi(double a) => AngouriMath.Numerics.SpecialFunctions.Phi(a);
308308
public static float Phi(float a) => (float)AngouriMath.Numerics.SpecialFunctions.Phi(a);
309-
public static long Phi(long a) => a.Phi();
310-
public static int Phi(int a) => (int)((long)a).Phi();
309+
public static long Phi(long a) => PeterO.Numbers.EInteger.FromInt64(a).Phi().ToInt64Checked();
310+
public static int Phi(int a) => PeterO.Numbers.EInteger.FromInt32(a).Phi().ToInt32Checked();
311311
public static BigInteger Phi(BigInteger a) => PeterO.Numbers.EInteger.FromBytes(a.ToByteArray(), littleEndian: true).Phi().ToBigInteger();
312312

313313
// The special functions, in double precision as the kernels define them, and the factorial,

‎Sources/AngouriMath/Functions/Compilation/IntoLinq/MathAllMethods.tt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,8 +225,8 @@ namespace AngouriMath.Core.Compilation.IntoLinq
225225
public static System.Numerics.Complex Phi(System.Numerics.Complex a) => AngouriMath.Numerics.SpecialFunctions.Phi(a);
226226
public static double Phi(double a) => AngouriMath.Numerics.SpecialFunctions.Phi(a);
227227
public static float Phi(float a) => (float)AngouriMath.Numerics.SpecialFunctions.Phi(a);
228-
public static long Phi(long a) => a.Phi();
229-
public static int Phi(int a) => (int)((long)a).Phi();
228+
public static long Phi(long a) => PeterO.Numbers.EInteger.FromInt64(a).Phi().ToInt64Checked();
229+
public static int Phi(int a) => PeterO.Numbers.EInteger.FromInt32(a).Phi().ToInt32Checked();
230230
public static BigInteger Phi(BigInteger a) => PeterO.Numbers.EInteger.FromBytes(a.ToByteArray(), littleEndian: true).Phi().ToBigInteger();
231231

232232
// The special functions, in double precision as the kernels define them, and the factorial,

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,9 @@ protected override Entity InnerSimplify(bool isExact)
786786
=> ExpandOnOneArgument(Argument,
787787
a => a switch
788788
{
789-
Integer integer => integer.Phi(),
789+
// Left as written where the argument cannot be factorised, rather than throwing out of a
790+
// simplification. https://github.com/asc-community/AngouriMath/issues/2342
791+
Integer integer => integer.EInteger.TryPhi() is { } totient ? Integer.Create(totient) : null,
790792
Number n => MathS.NaN,
791793
_ => null
792794
},

‎Sources/AngouriMath/Functions/InternalAMExtensions.cs‎

Lines changed: 112 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -321,106 +321,151 @@ public static EInteger Lcm(this EInteger bigintFirst, EInteger bigintSecond) =>
321321
public static EInteger Combinations(this EInteger n, EInteger k) =>
322322
n.Factorial() / ((n - k).Factorial() * k.Factorial());
323323

324+
/// <summary>
325+
/// Euler's totient of <paramref name="n"/>, 0 for an <paramref name="n"/> that is not positive, or
326+
/// <see langword="null"/> where <paramref name="n"/> cannot be factorised (<see cref="TryFactorize"/>).
327+
/// <a href="https://en.wikipedia.org/wiki/Euler%27s_totient_function"/>
328+
/// </summary>
329+
internal static EInteger? TryPhi(this EInteger n)
330+
{
331+
if (n.Sign <= 0)
332+
return EInteger.Zero;
333+
if (n.TryFactorize() is not { } factors)
334+
return null;
335+
var result = EInteger.One;
336+
foreach (var (prime, power) in factors)
337+
result *= prime.Pow(power - 1) * (prime - 1);
338+
return result;
339+
}
340+
324341
/// <summary>
325342
/// Computes Euler phi function
326343
/// <a href="https://en.wikipedia.org/wiki/Euler%27s_totient_function"/>
327344
/// </summary>
328345
/// If integer x is non-positive, the result will be 0
329346
public static EInteger Phi(this EInteger n)
330-
{
331-
if (n <= 0)
332-
return 0;
347+
=> n.TryPhi() ?? throw Unfactorised(n);
333348

334-
var result = n.ToInt64Checked();
335-
var original = result;
349+
/// <summary>
350+
/// Factorization of integer
351+
/// </summary>
352+
public static IEnumerable<(EInteger prime, EInteger power)> Factorize(this EInteger n)
353+
=> n.TryFactorize() ?? throw Unfactorised(n);
336354

337-
for (long i = 2; i * i <= result; i++) {
338-
if (original % i == 0)
339-
{
340-
while (original % i == 0) original /= i;
341-
result -= result / i;
342-
}
343-
}
355+
private static NotSufficientlySupportedException Unfactorised(EInteger n)
356+
=> new($"{n} has a factor that is neither proven prime nor split, and is not factorised");
344357

345-
if (original > 1)
346-
result -= result / original;
358+
/// <summary>How far trial division goes before the rest is asked whether it is prime.</summary>
359+
private const int TrialDivisionLimit = 1 << 16;
360+
361+
/// <summary>How many steps Pollard's rho takes, for each of its constants, before it gives up on a split.</summary>
362+
private const int RhoSteps = 1 << 18;
347363

348-
return result;
349-
}
350364
/// <summary>
351-
/// Computes Euler phi function (for long)
352-
/// <a href="https://en.wikipedia.org/wiki/Euler%27s_totient_function"/>
365+
/// The prime factorisation of <paramref name="n"/>, the primes in increasing order, empty for an
366+
/// <paramref name="n"/> below 2, or <see langword="null"/> where a factor is neither proven prime nor split.
353367
/// </summary>
354-
/// If integer x is non-positive, the result will be 0
355-
public static long Phi(this long n)
368+
/// <remarks>
369+
/// This was trial division over <c>long</c>, and for every <paramref name="n"/> past 2^63 it threw
370+
/// <c>OverflowException</c>, though the first division finds a factor like 2 or 7 at any size: <c>phi(7^30)</c>
371+
/// threw from <c>Simplify</c>. Its loop ran while the square of the divisor was at most the running totient,
372+
/// not what was left to factor, so <c>2^62</c> took 1.5e9 divisions after the first had divided every 2 out;
373+
/// and past 3037000499 that square wrapped negative, so the largest prime below 2^63 never finished. Now trial
374+
/// division in <see cref="EInteger"/> to <see cref="TrialDivisionLimit"/>, bounded by what is left, then
375+
/// <see cref="Primes.IsPrime"/>, Miller–Rabin and Lucas–Lehmer, for the rest, and Pollard's rho to split a
376+
/// rest that is composite. https://github.com/asc-community/AngouriMath/issues/2342
377+
/// </remarks>
378+
internal static List<(EInteger Prime, EInteger Power)>? TryFactorize(this EInteger n)
356379
{
357-
if (n <= 0)
358-
return 0;
359-
360-
var result = n;
361-
var original = result;
362-
363-
for (long i = 2; i * i <= result; i++)
380+
var byPrime = new SortedDictionary<EInteger, EInteger>();
381+
if (n.CompareTo(EInteger.FromInt32(2)) < 0)
382+
return new();
383+
var rest = n;
384+
void Add(EInteger prime, EInteger power)
385+
=> byPrime[prime] = (byPrime.TryGetValue(prime, out var already) ? already : EInteger.Zero) + power;
386+
for (var divisor = 2; divisor <= TrialDivisionLimit; divisor += divisor == 2 ? 1 : 2)
364387
{
365-
if (original % i == 0)
388+
var asInteger = EInteger.FromInt32(divisor);
389+
if (asInteger * asInteger > rest)
390+
break;
391+
var power = EInteger.Zero;
392+
while (rest.Remainder(asInteger).IsZero)
366393
{
367-
while (original % i == 0) original /= i;
368-
result -= result / i;
394+
rest /= asInteger;
395+
power += 1;
369396
}
397+
if (!power.IsZero)
398+
Add(asInteger, power);
370399
}
371-
372-
if (original > 1)
373-
result -= result / original;
374-
375-
return result;
400+
var pending = new Stack<EInteger>();
401+
if (!rest.Equals(EInteger.One))
402+
pending.Push(rest);
403+
while (pending.Count > 0)
404+
{
405+
Core.Multithreading.MultithreadingFunctional.ExitIfCancelled();
406+
var factor = pending.Pop();
407+
// Past the trial division a factor whose square is past it has no divisor it did not try.
408+
var limit = EInteger.FromInt32(TrialDivisionLimit);
409+
var isPrime = factor.CompareTo(limit * limit) <= 0 ? true : Primes.IsPrime(factor);
410+
if (isPrime is true)
411+
{
412+
Add(factor, EInteger.One);
413+
continue;
414+
}
415+
if (isPrime is null || PollardRho(factor) is not { } split)
416+
return null;
417+
pending.Push(split);
418+
pending.Push(factor / split);
419+
}
420+
var factors = new List<(EInteger, EInteger)>(byPrime.Count);
421+
foreach (var pair in byPrime)
422+
factors.Add((pair.Key, pair.Value));
423+
return factors;
376424
}
377425

378-
/// <summary>
379-
/// Factorization of integer
380-
/// </summary>
381-
public static IEnumerable<(long prime, long power)> Factorize(this EInteger n)
426+
/// <summary>A proper divisor of the odd composite <paramref name="n"/>, or <see langword="null"/>.</summary>
427+
private static EInteger? PollardRho(EInteger n)
382428
{
383-
var result = n.ToInt64Checked();
384-
var original = result;
385-
386-
for (long i = 2; i * i <= result; i++)
429+
for (var constant = 1; constant <= 4; constant++)
387430
{
388-
if (original % i == 0)
431+
var c = EInteger.FromInt32(constant);
432+
EInteger Step(EInteger x) => (x * x + c).Remainder(n);
433+
var (slow, fast, divisor) = (EInteger.FromInt32(2), EInteger.FromInt32(2), EInteger.One);
434+
for (var step = 0; step < RhoSteps && divisor.Equals(EInteger.One); step++)
389435
{
390-
long power = 0;
391-
while (original % i == 0)
392-
{
393-
original /= i;
394-
power++;
395-
}
396-
397-
result -= result / i;
398-
yield return (i, power);
436+
slow = Step(slow);
437+
fast = Step(Step(fast));
438+
divisor = (slow - fast).Abs().Gcd(n);
399439
}
440+
if (!divisor.Equals(EInteger.One) && !divisor.Equals(n))
441+
return divisor;
400442
}
401-
402-
if (original > 1)
403-
yield return (original, 1L);
443+
return null;
404444
}
405445

406446
/// <summary>
407-
/// Count of all divisors of an integer
447+
/// The number of divisors of <paramref name="n"/>, 0 for an <paramref name="n"/> that is not positive, or
448+
/// <see langword="null"/> where it cannot be factorised.
408449
/// </summary>
409-
/// If integer x is non-positive, the result will be 0
410-
public static EInteger CountDivisors(this EInteger n)
450+
internal static EInteger? TryCountDivisors(this EInteger n)
411451
{
412-
if (n <= 0)
413-
return 0;
414-
415-
EInteger result = 1;
416-
foreach ((var prime, var power) in Factorize(n))
417-
{
452+
if (n.Sign <= 0)
453+
return EInteger.Zero;
454+
if (n.TryFactorize() is not { } factors)
455+
return null;
456+
var result = EInteger.One;
457+
foreach (var (_, power) in factors)
418458
result *= power + 1;
419-
}
420-
421459
return result;
422460
}
423461

462+
/// <summary>
463+
/// Count of all divisors of an integer
464+
/// </summary>
465+
/// If integer x is non-positive, the result will be 0
466+
public static EInteger CountDivisors(this EInteger n)
467+
=> n.TryCountDivisors() ?? throw Unfactorised(n);
468+
424469
public static bool GreaterThan(this EDecimal bigDecimalOne, EDecimal bigDecimalTwo) =>
425470
bigDecimalOne.CompareTo(bigDecimalTwo) > 0;
426471
public static bool GreaterThanOrEquals(this EDecimal bigDecimalOne, EDecimal bigDecimalTwo) =>

‎Sources/AngouriMath/Functions/Simplification/Patterns/Patterns.NumberTheory.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ internal static partial class Patterns
1414
[AddressableRules]
1515
internal static Entity PhiFunctionRules(Entity x) => x switch
1616
{
17-
Phif(Powf(Integer prime, var variable)) when prime.IsPrime => new Powf(prime, variable - 1) * (prime - 1),
17+
Phif(Powf(Integer prime, var variable)) when Primes.IsPrime(prime.EInteger) is true => new Powf(prime, variable - 1) * (prime - 1),
1818
_ => x
1919
};
2020
}

‎Sources/AngouriMath/Numerics/SpecialFunctions.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,8 @@ private static NumericsComplex LogSine(NumericsComplex w)
503503
public static NumericsComplex Phi(NumericsComplex z) => z.Imaginary == 0 ? Phi(z.Real) : NaN;
504504

505505
public static double Phi(double x)
506-
=> x == Math.Floor(x) && x >= long.MinValue && x < long.MaxValue ? ((long)x).Phi() : double.NaN;
506+
=> x == Math.Floor(x) && x >= long.MinValue && x < long.MaxValue && PeterO.Numbers.EInteger.FromInt64((long)x).TryPhi() is { } totient
507+
? PeterO.Numbers.EDecimal.FromEInteger(totient).ToDouble() : double.NaN;
507508

508509
/// <summary>
509510
/// Half of <paramref name="value"/>, part by part: dividing a complex number by 2 multiplies it

0 commit comments

Comments
 (0)