Replace heuristic sqrt with log2-based estimate

This commit is contained in:
Marek Lemańczyk committed 2025-10-29 01:29:12 +01:00
1 parent eeeff42be6
commit 5a9e103bd5
2 files changed
+26 -32

No files matched your search

+13 -16
View File
@@ -436,31 +436,28 @@ Cleanup:
return n;
}
ulong bit = 1UL << 62;
while (bit > n)
int log2 = BitOperations.Log2(n);
ulong estimate = 1UL << ((log2 + 1) >> 1);
ulong quotient = n / estimate;
while (estimate > quotient)
{
bit >>= 2;
estimate = (estimate + quotient) >> 1;
quotient = n / estimate;
}
ulong result = 0UL;
ulong remainder = n;
while (bit != 0)
while (true)
{
ulong candidate = result + bit;
if (remainder >= candidate)
ulong nextEstimate = estimate + 1UL;
if (nextEstimate > n / nextEstimate)
{
remainder -= candidate;
result = (result >> 1) + bit;
}
else
{
result >>= 1;
break;
}
bit >>= 2;
estimate = nextEstimate;
}
return result;
return estimate;
}
private static ReadOnlySpan<byte> GetGroupBEndingOrder(byte nMod10) => nMod10 switch