Fix carry and modulus offset in bigint
This commit is contained in:
parent
3033ae30f8
commit
ade919b003
|
@ -256,12 +256,9 @@ func shlAddMod[bits](a: var BigInt[bits], c: Word, M: BigInt[bits]) =
|
|||
block: # q*p
|
||||
var qp_hi: Word
|
||||
unsafeExtendedPrecMul(qp_hi, qp_lo, q, M.limbs[i]) # q * p
|
||||
# assert qp_lo.isMsbSet.not.bool
|
||||
# assert carry.isMsbSet.not.bool
|
||||
qp_lo += carry # Add carry from previous limb
|
||||
let qp_carry = qp_lo.isMsbSet
|
||||
carry = mux(qp_carry, qp_hi + One, qp_hi) # New carry
|
||||
|
||||
carry = qp_hi shl 1 + qp_lo.isMsbSet.Word # New carry
|
||||
qp_lo = qp_lo and MaxWord # Normalize to u63
|
||||
|
||||
block: # a*2^63 - q*p
|
||||
|
@ -312,5 +309,5 @@ func reduce*[aBits, mBits](r: var BigInt[mBits], a: BigInt[aBits], M: BigInt[mBi
|
|||
const aOffset = a.limbs.len - M.limbs.len
|
||||
copyLimbs(r, 0, a, aOffset, M.limbs.len - 1)
|
||||
r.limbs[^1] = Zero
|
||||
for i in countdown(aOffset, 0):
|
||||
for i in countdown(aOffset-1, 0):
|
||||
r.shlAddMod(a.limbs[i], M)
|
||||
|
|
|
@ -160,29 +160,29 @@ suite "Modular operations - small modulus - Stint specific failures highlighted
|
|||
let v = 174261910798982'u64
|
||||
|
||||
let a = BigInt[64].fromUint(u)
|
||||
let m = BigInt[48].fromUint(v)
|
||||
let m = BigInt[49].fromUint(v)
|
||||
|
||||
var r: BigInt[48]
|
||||
var r: BigInt[49]
|
||||
r.reduce(a, m)
|
||||
# Copy the result in a conveniently sized buffer
|
||||
var rr: BigInt[48]
|
||||
var rr: BigInt[49]
|
||||
copyLimbs(rr, 0, r, 0, r.limbs.len)
|
||||
|
||||
check:
|
||||
bool(rr == BigInt[48].fromUint(u mod v))
|
||||
bool(rr == BigInt[49].fromUint(u mod v))
|
||||
|
||||
test "Modulo: 15080397990160655 mod 600432699691":
|
||||
let u = 15080397990160655'u64
|
||||
let v = 600432699691'u64
|
||||
|
||||
let a = BigInt[64].fromUint(u)
|
||||
let m = BigInt[40].fromUint(v)
|
||||
let m = BigInt[41].fromUint(v)
|
||||
|
||||
var r: BigInt[40]
|
||||
var r: BigInt[41]
|
||||
r.reduce(a, m)
|
||||
# Copy the result in a conveniently sized buffer
|
||||
var rr: BigInt[40]
|
||||
var rr: BigInt[41]
|
||||
copyLimbs(rr, 0, r, 0, r.limbs.len)
|
||||
|
||||
check:
|
||||
bool(rr == BigInt[40].fromUint(u mod v))
|
||||
bool(rr == BigInt[41].fromUint(u mod v))
|
||||
|
|
Loading…
Reference in New Issue