Skip to content

Improve powmod #135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 9 additions & 11 deletions src/bigints.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1244,7 +1244,7 @@ func fastLog2*(a: BigInt): int =
## If `a` is zero, returns -1.
if a.isZero:
return -1
bitops.fastLog2(a.limbs[^1]) + 32*(a.limbs.high)
bitops.fastLog2(a.limbs[^1]) + 32 * (a.limbs.high)


func invmod*(a, modulus: BigInt): BigInt =
Expand Down Expand Up @@ -1284,23 +1284,21 @@ func powmod*(base, exponent, modulus: BigInt): BigInt =
## The return value is always in the range `[0, modulus-1]`.
runnableExamples:
assert powmod(2.initBigInt, 3.initBigInt, 7.initBigInt) == 1.initBigInt

if modulus.isZero:
raise newException(DivByZeroDefect, "modulus must be nonzero")
elif modulus.isNegative:
raise newException(ValueError, "modulus must be strictly positive")
elif modulus == 1:
return zero
else:
var
base = base
exponent = exponent
if exponent < 0:
base = invmod(base, modulus)
exponent = -exponent
var basePow = base.modulo(modulus)
var basePow =
if exponent < 0:
invmod(base, modulus)
else:
base.modulo(modulus)
result = one
while not exponent.isZero:
if (exponent.limbs[0] and 1) != 0:
for i in 0..fastLog2(exponent):
if (exponent.limbs[i div 32] and (1'u32 shl (i mod 32))) != 0:
result = (result * basePow) mod modulus
basePow = (basePow * basePow) mod modulus
exponent = exponent shr 1