@@ -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 ) =>
0 commit comments