Skip to content
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

fixed the overflow problem of powermod(x::Integer, p::Integer, m::T) #48192

Merged
merged 14 commits into from
Jan 11, 2023
Merged
Show file tree
Hide file tree
Changes from 12 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
13 changes: 12 additions & 1 deletion base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -369,8 +369,19 @@ julia> powermod(5, 3, 19)
```
"""
function powermod(x::Integer, p::Integer, m::T) where T<:Integer
p < 0 && return powermod(invmod(x, m), -p, m)
p == 0 && return mod(one(m),m)
# When the concrete type of p is sigened and has the lowerst value,
StonerShaw marked this conversation as resolved.
Show resolved Hide resolved
# `p != 0 && p == -p` is equivalent to `p == typemin(typeof(p))` for 2's complement representation.
# but will work for integer types like `BigInt` that don't have `typemin` defined
# It needs special handling otherwise will cause overflow problem.
if p == -p
t = powermod(invmod(x, m), -(p÷2), m)
t = mod(widemul(t, t), m)
iseven(p) && return t
#else odd
return mod(widemul(t, invmod(x, m)), m)
end
p < 0 && return powermod(invmod(x, m), -p, m)
(m == 1 || m == -1) && return zero(m)
b = oftype(m,mod(x,m)) # this also checks for divide by zero

Expand Down
6 changes: 6 additions & 0 deletions test/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,12 @@ end
@test powermod(2, -2, 5) == 4
@test powermod(2, -1, -5) == -2
@test powermod(2, -2, -5) == -1

@test powermod(2, typemin(Int128), 5) == 1
@test powermod(2, typemin(Int128), -5) == -4
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a test for BigInt power to make sure this still works for types without typemin.


@test powermod(2, big(3), 5) == 3
@test powermod(2, big(3), -5) == -2
end

@testset "nextpow/prevpow" begin
Expand Down