Reapply modulo helpers and inline fast remainders

This commit is contained in:
Marek Lemańczyk committed 2025-09-22 19:26:07 +02:00
1 parent 5db0c4fa95
commit ca866ffc5b
43 files changed
+982 -134

No files matched your search

@@ -11,37 +11,44 @@ public class Mod10_8_5_3Benchmarks
public ulong Value { get; set; }
[Benchmark(Baseline = true)]
public (ulong Mod10, ulong Mod8, ulong Mod3, ulong Mod5) ModuloOperator()
{
ulong value = Value;
return (value % 10UL, value % 8UL, value % 3UL, value % 5UL);
}
[Benchmark]
public (ulong Mod10, ulong Mod8, ulong Mod3, ulong Mod5) LegacyModulo()
{
ulong mod10, mod8, mod3, mod5;
UInt128 zero = UInt128.Zero;
if (Value == zero)
{
mod3 = 0UL;
mod5 = 0UL;
mod8 = 0UL;
mod10 = 0UL;
return (mod10, mod8, mod3, mod5);
}
ulong mod10, mod8, mod3, mod5;
UInt128 zero = UInt128.Zero;
if (Value == zero)
{
mod3 = 0UL;
mod5 = 0UL;
mod8 = 0UL;
mod10 = 0UL;
return (mod10, mod8, mod3, mod5);
}
UInt128 high = Value >> 64;
ulong result = Value;
mod8 = result & 7UL;
// 2^64 ≡ 1 (mod 3)
ulong modRem = (result % 3UL) + ((ulong)high % 3UL);
mod3 = modRem >= 3UL ? modRem - 3UL : modRem;
// 2^64 ≡ 1 (mod 5)
modRem = (result % 5UL) + ((ulong)high % 5UL);
mod5 = modRem >= 5UL ? modRem - 5UL : modRem;
UInt128 high = Value >> 64;
ulong result = Value;
mod8 = result & 7UL;
// 2^64 ≡ 1 (mod 3)
ulong modRem = (result % 3UL) + ((ulong)high % 3UL);
mod3 = modRem >= 3UL ? modRem - 3UL : modRem;
// 2^64 ≡ 1 (mod 5)
modRem = (result % 5UL) + ((ulong)high % 5UL);
mod5 = modRem >= 5UL ? modRem - 5UL : modRem;
while (high != zero)
{
// 2^64 ≡ 6 (mod 10)
result = (result + (ulong)high * 6UL) % 10UL;
high >>= 64;
}
while (high != zero)
{
// 2^64 ≡ 6 (mod 10)
result = (result + (ulong)high * 6UL) % 10UL;
high >>= 64;
}
mod10 = result % 10UL;
mod10 = result % 10UL;
return (mod10, mod8, mod3, mod5);
}