Merge pull request #88 from mlemanczyk/codex/fix-divisor-cycle-handling-in-gpu-mode

Filter disallowed divisors when scanning by divisor
This commit is contained in:
Marek Lemańczyk authored and GitHub committed 2025-09-25 10:04:59 +02:00
commit 5bfc9b1c30
1 file changed
+49 -8
+49 -8
View File
@@ -1019,13 +1019,10 @@ internal static class Program
ref long nextDivisorBits = ref Unsafe.As<ulong, long>(ref nextDivisor); ref long nextDivisorBits = ref Unsafe.As<ulong, long>(ref nextDivisor);
ulong blockStride = unchecked(DivisorAllocationBlockSize * 2); ulong blockStride = unchecked(DivisorAllocationBlockSize * 2);
if (localDivisorsRemaining > 0) if (TryAcquireLocalDivisor(ref localDivisorCursor, ref localDivisorsRemaining, out ulong localDivisor))
{ {
ulong currentValue = localDivisorCursor;
localDivisorCursor += 2UL;
localDivisorsRemaining--;
exhausted = false; exhausted = false;
return currentValue; return localDivisor;
} }
while (true) while (true)
@@ -1074,11 +1071,55 @@ internal static class Program
continue; continue;
} }
localDivisorCursor = currentValue + 2UL; localDivisorCursor = currentValue;
localDivisorsRemaining = count - 1; localDivisorsRemaining = count;
if (TryAcquireLocalDivisor(ref localDivisorCursor, ref localDivisorsRemaining, out ulong candidate))
{
exhausted = false; exhausted = false;
return currentValue; return candidate;
} }
// No valid divisor was found in this range; attempt to acquire the next block.
localDivisorCursor = 0UL;
localDivisorsRemaining = 0;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryAcquireLocalDivisor(ref ulong cursor, ref int remaining, out ulong divisor)
{
while (remaining > 0)
{
ulong candidate = cursor;
cursor += 2UL;
remaining--;
if (IsAllowedDivisorCandidate(candidate))
{
divisor = candidate;
return true;
}
}
divisor = 0UL;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsAllowedDivisorCandidate(ulong divisor)
{
if ((divisor & 1UL) == 0UL)
{
return false;
}
if ((divisor % 3UL) == 0UL || (divisor % 5UL) == 0UL || (divisor % 7UL) == 0UL || (divisor % 11UL) == 0UL)
{
return false;
}
return true;
} }
private static int BuildPrimeBuffer(ulong divisor, in ulong[] primeValues, in ulong[] allowedMaxValues, int[] stateFlags, ulong[] primeBuffer, int[] indexBuffer, PendingResult[] completionsBuffer, ref int completionsCount, ref int remainingStates, long[] activeStateMask, ref int activeStartIndex) private static int BuildPrimeBuffer(ulong divisor, in ulong[] primeValues, in ulong[] allowedMaxValues, int[] stateFlags, ulong[] primeBuffer, int[] indexBuffer, PendingResult[] completionsBuffer, ref int completionsCount, ref int remainingStates, long[] activeStateMask, ref int activeStartIndex)