Merge pull request #51 from mlemanczyk/codex/optimize-uint128extensions.mod10_8_5_3-method
Optimize Mod10_8_5_3 remainder computation
This commit is contained in:
1 file changed
+44
-22
@@ -123,34 +123,56 @@ public static class UInt128Extensions
|
|||||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
public static void Mod10_8_5_3(this UInt128 value, out ulong mod10, out ulong mod8, out ulong mod5, out ulong mod3)
|
public static void Mod10_8_5_3(this UInt128 value, out ulong mod10, out ulong mod8, out ulong mod5, out ulong mod3)
|
||||||
{
|
{
|
||||||
UInt128 zero = UInt128.Zero;
|
UInt128 temp = value;
|
||||||
if (value == zero)
|
uint byteSum = 0U;
|
||||||
|
|
||||||
|
do
|
||||||
{
|
{
|
||||||
mod3 = 0UL;
|
byteSum += (uint)(byte)temp;
|
||||||
mod5 = 0UL;
|
temp >>= 8;
|
||||||
mod8 = 0UL;
|
}
|
||||||
mod10 = 0UL;
|
while (temp != UInt128.Zero);
|
||||||
return;
|
|
||||||
|
mod8 = (ulong)value & 7UL;
|
||||||
|
|
||||||
|
uint mod5Value = FastRemainder5(byteSum);
|
||||||
|
uint mod3Value = FastRemainder3(byteSum);
|
||||||
|
|
||||||
|
ulong parity = mod8 & 1UL;
|
||||||
|
mod10 = parity == 0UL
|
||||||
|
? mod5Value switch
|
||||||
|
{
|
||||||
|
0U => 0UL,
|
||||||
|
1U => 6UL,
|
||||||
|
2U => 2UL,
|
||||||
|
3U => 8UL,
|
||||||
|
_ => 4UL,
|
||||||
|
}
|
||||||
|
: mod5Value switch
|
||||||
|
{
|
||||||
|
0U => 5UL,
|
||||||
|
1U => 1UL,
|
||||||
|
2U => 7UL,
|
||||||
|
3U => 3UL,
|
||||||
|
_ => 9UL,
|
||||||
|
};
|
||||||
|
|
||||||
|
mod5 = mod5Value;
|
||||||
|
mod3 = mod3Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
UInt128 high = value >> 64;
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
ulong result = (ulong)value;
|
private static uint FastRemainder3(uint 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)
|
uint quotient = (uint)(((ulong)value * 0xAAAAAAABUL) >> 33);
|
||||||
result = (result + (ulong)high * 6UL) % 10UL;
|
return value - quotient * 3U;
|
||||||
high >>= 64;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mod10 = result % 10UL;
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static uint FastRemainder5(uint value)
|
||||||
|
{
|
||||||
|
uint quotient = (uint)(((ulong)value * 0xCCCCCCCDUL) >> 34);
|
||||||
|
return value - quotient * 5U;
|
||||||
}
|
}
|
||||||
|
|
||||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
|||||||
Reference in new issue
Block a user