Reuse stack buffers when lowering divisor exponents

This commit is contained in:
Marek Lemańczyk committed 2025-10-21 18:22:56 +02:00
1 parent 1b3a89ca53
commit c15405e3b1
4 files changed
+497 -172

No files matched your search

+103 -38
View File
@@ -304,7 +304,8 @@ public class MersenneDivisorCycles
// return false;
// }
Dictionary<ulong, int> factorCounts = ThreadStaticPools.RentFactorCountDictionary();
// Each divisor candidate is evaluated once along the scan, so a fresh factor map per call avoids keeping an unused cache.
Dictionary<ulong, int> factorCounts = new Dictionary<ulong, int>();
bool success = false;
if (twoCount > 0)
@@ -322,7 +323,6 @@ public class MersenneDivisorCycles
primeOrderFailed = false;
}
ThreadStaticPools.ReturnFactorCountDictionary(factorCounts);
return success;
}
@@ -335,12 +335,11 @@ public class MersenneDivisorCycles
return true;
}
Dictionary<ulong, int> scratch = ThreadStaticPools.RentFactorScratchDictionary();
// Factorizations are local to a single reduction attempt; there is no reuse across calls.
Dictionary<ulong, int> scratch = new Dictionary<ulong, int>();
bool success = TryFactorIntoCountsInternal(value, scratch);
if (!success)
{
// The scan recalculates factors every time; the old cache never produced hits.
ThreadStaticPools.ReturnFactorScratchDictionary(scratch);
return false;
}
@@ -350,7 +349,6 @@ public class MersenneDivisorCycles
AddFactor(counts, pair.Key, pair.Value);
}
ThreadStaticPools.ReturnFactorScratchDictionary(scratch);
return true;
}
@@ -459,48 +457,115 @@ public class MersenneDivisorCycles
}
int count = factorCounts.Count;
ulong[] primes = ArrayPool<ulong>.Shared.Rent(count);
try
ulong[] primes = ThreadStaticPools.UlongPool.Rent(count);
int index = 0;
foreach (KeyValuePair<ulong, int> entry in factorCounts)
{
int index = 0;
foreach (KeyValuePair<ulong, int> entry in factorCounts)
primes[index] = entry.Key;
index++;
}
Array.Sort(primes, 0, count);
ulong order = initialOrder;
int stackMultiplicity = 0;
for (int i = 0; i < count; i++)
{
int multiplicity = factorCounts[primes[i]];
if (multiplicity <= 16 && multiplicity > stackMultiplicity)
{
primes[index] = entry.Key;
index++;
stackMultiplicity = multiplicity;
}
}
Span<ulong> stackCandidates = stackMultiplicity > 0 ? stackalloc ulong[stackMultiplicity] : Span<ulong>.Empty;
Span<bool> stackEvaluations = stackMultiplicity > 0 ? stackalloc bool[stackMultiplicity] : Span<bool>.Empty;
for (int i = 0; i < count; i++)
{
ulong prime = primes[i];
int multiplicity = factorCounts[prime];
// Multiplicities collected by TryFactorIntoCountsInternal are strictly positive along the scanner path.
// Keeping the guard commented documents the assumption so it does not resurface in future reviews.
// if (multiplicity <= 0)
// {
// continue;
// }
if (multiplicity <= 16)
{
ProcessReduceOrderPrime(stackCandidates.Slice(0, multiplicity), stackEvaluations.Slice(0, multiplicity), ref order, prime, multiplicity, divisorData);
}
else
{
ulong[] rentedCandidates = ThreadStaticPools.UlongPool.Rent(multiplicity);
bool[] rentedEvaluations = ThreadStaticPools.BoolPool.Rent(multiplicity);
ProcessReduceOrderPrime(rentedCandidates.AsSpan(0, multiplicity), rentedEvaluations.AsSpan(0, multiplicity), ref order, prime, multiplicity, divisorData);
ThreadStaticPools.UlongPool.Return(rentedCandidates, clearArray: false);
ThreadStaticPools.BoolPool.Return(rentedEvaluations, clearArray: false);
}
}
ThreadStaticPools.UlongPool.Return(primes, clearArray: false);
return order;
}
private static void ProcessReduceOrderPrime(Span<ulong> candidateBuffer, Span<bool> evaluationBuffer, ref ulong order, ulong prime, int multiplicity, in MontgomeryDivisorData divisorData)
{
ulong working = order;
int actual = 0;
while (actual < multiplicity)
{
if (working < prime)
{
break;
}
Array.Sort(primes, 0, count);
ulong order = initialOrder;
for (int i = 0; i < count; i++)
ulong reduced = working / prime;
if (reduced == 0UL)
{
ulong prime = primes[i];
int multiplicity = factorCounts[prime];
for (int iteration = 0; iteration < multiplicity; iteration++)
{
if (order % prime != 0UL)
{
break;
}
ulong candidate = order / prime;
if (candidate.Pow2MontgomeryModWindowedCpu(divisorData, keepMontgomery: false) == 1UL)
{
order = candidate;
continue;
}
break;
}
break;
}
return order;
candidateBuffer[actual] = reduced;
working = reduced;
actual++;
}
finally
if (actual == 0)
{
ArrayPool<ulong>.Shared.Return(primes, clearArray: false);
return;
}
Span<ulong> candidates = candidateBuffer.Slice(0, actual);
Span<bool> evaluations = evaluationBuffer.Slice(0, actual);
for (int left = 0, right = actual - 1; left < right; left++, right--)
{
ulong tmp = candidates[left];
candidates[left] = candidates[right];
candidates[right] = tmp;
}
ExponentRemainderStepper stepper = ThreadStaticPools.RentExponentStepper(divisorData);
for (int j = 0; j < actual; j++)
{
evaluations[j] = stepper.ComputeNextIsUnity(candidates[j]);
}
for (int j = actual - 1; j >= 0; j--)
{
if (!evaluations[j])
{
break;
}
order = candidates[j];
}
ThreadStaticPools.ReturnExponentStepper(stepper);
}
private static ulong PollardRho64(ulong n)