Restore GPU-backed UInt128 pow2 Montgomery helper

This commit is contained in:
Marek Lemańczyk committed 2025-10-05 02:13:31 +02:00
1 parent 7ffd438eee
commit 0bc97937aa
11 files changed
+1561 -30

No files matched your search

+57
View File
@@ -54,6 +54,26 @@ public struct GpuUInt128 : IComparable<GpuUInt128>, IEquatable<GpuUInt128>
get => High == 0UL && Low == 0UL;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly int GetBitLength()
{
if (High != 0UL)
{
return 64 + (64 - BitOperations.LeadingZeroCount(High));
}
ulong low = Low;
if (low == 0UL)
{
return 0;
}
return 64 - BitOperations.LeadingZeroCount(low);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetBitLength(GpuUInt128 value) => value.GetBitLength();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator GpuUInt128(UInt128 value) => new(value);
@@ -564,6 +584,43 @@ public struct GpuUInt128 : IComparable<GpuUInt128>, IEquatable<GpuUInt128>
Low = lowPart;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GpuUInt128 DivideExact(GpuUInt128 dividend, GpuUInt128 divisor)
{
int divisorBits = divisor.GetBitLength();
int shift = dividend.GetBitLength() - divisorBits;
GpuUInt128 quotient = Zero;
GpuUInt128 remainder = dividend;
GpuUInt128 shiftedDivisor = divisor << shift;
GpuUInt128 quotientBit = One << shift;
while (true)
{
if (remainder.CompareTo(shiftedDivisor) >= 0)
{
remainder.Sub(shiftedDivisor);
quotient.Add(quotientBit);
}
if (shift == 0)
{
break;
}
shift--;
shiftedDivisor.ShiftRight(1);
quotientBit.ShiftRight(1);
}
if (!remainder.IsZero)
{
throw new InvalidOperationException("DivideExact requires divisible operands.");
}
return quotient;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Xor(GpuUInt128 other)
{