% 10 operations replaces with UInt128/ulong.Mod10 methods

This commit is contained in:
Marek Lemańczyk committed 2025-09-21 07:42:25 +02:00
1 parent 3e0102a404
commit 412ce4fd50
13 files changed
+256 -195

No files matched your search

@@ -0,0 +1,52 @@
using BenchmarkDotNet.Attributes;
using PerfectNumbers.Core;
namespace EvenPerfectBitScanner.Benchmarks;
[MemoryDiagnoser]
public class Mod10UInt128Benchmarks
{
[Params(3UL, 8191UL, 131071UL, 2147483647UL)]
public UInt128 Value { get; set; }
[Benchmark(Baseline = true)]
public UInt128 StandardModulo()
{
return Value % 10UL;
}
[Benchmark]
public ulong ModWithHighLowModulo()
{
// Split and fold under mod 10: 2^64 ≡ 6 (mod 10)
ulong value = (ulong)Value;
ulong high = value >> 64;
ulong low = value;
ulong highRem = high.Mod10();
ulong lowRem = low.Mod10();
ulong combined = lowRem + highRem * 6UL;
return combined.Mod10();
}
[Benchmark]
public ulong ModWithLoopModulo()
{
UInt128 value = Value;
UInt128 zero = UInt128.Zero;
if (value == zero)
return 0UL;
ulong result = (ulong)value;
UInt128 high = value >> 64;
while (high != zero)
{
// 2^64 ≡ 6 (mod 10)
result = (result + (ulong)high * 6UL).Mod10();
high >>= 64;
}
return result.Mod10();
}
}
@@ -5,7 +5,7 @@ using PerfectNumbers.Core;
namespace EvenPerfectBitScanner.Benchmarks;
[MemoryDiagnoser]
public class Mod10Benchmarks
public class Mod10ULongBenchmarks
{
[Params(3UL, 8191UL, 131071UL, 2147483647UL)]
public ulong Value { get; set; }
@@ -13,14 +13,7 @@ public class Mod10Benchmarks
[Benchmark(Baseline = true)]
public ulong LegacyModulo()
{
ulong value = Value;
UInt128 zero = UInt128.Zero;
if (value == zero)
{
return 0UL;
}
return value % 10UL;
return Value % 10UL;
}
[Benchmark]
@@ -0,0 +1,33 @@
using System.Numerics;
using BenchmarkDotNet.Attributes;
using PerfectNumbers.Core;
namespace EvenPerfectBitScanner.Benchmarks;
[MemoryDiagnoser]
public class Mod10_8_5_3StepsBenchmarks
{
[Params(3UL, 8191UL, 131071UL, 2147483647UL)]
public ulong Value { get; set; }
[Benchmark(Baseline = true)]
public (ulong Mod10, ulong Mod8, ulong Mod3, ulong Mod5) LegacyModulo()
{
UInt128 value = Value;
ulong mod10 = (ulong)(value % 10UL) % 10UL;
ulong mod8 = (ulong)(value % 8UL);
ulong mod3 = (ulong)(value % 3UL);
ulong mod5 = (ulong)(value % 5UL);
return (mod10, mod8, mod3, mod5);
}
[Benchmark]
public (ulong Mod10, ulong Mod8, ulong Mod3, ulong Mod5) ModMethodModulo()
{
Value.Mod10_8_5_3(out ulong mod10, out ulong mod8, out ulong mod5, out ulong mod3);
// Step residues for q += 2*p
mod10 = mod10.Mod10();
return (mod10, mod8, mod3, mod5);
}
}