Skip to content

Commit

Permalink
simplify checks in powermod, and add more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffBezanson committed Nov 14, 2013
1 parent c517ce8 commit e9087e0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
8 changes: 4 additions & 4 deletions base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,10 @@ end
# b^p mod m
function powermod{T}(b::Integer, p::Integer, m::T)
p < 0 && throw(DomainError())
p == 0 && return m == 0 ? throw(DivideError()) : m < 0 ?
(m == -1 ? zero(promote_type(typeof(b),typeof(m))) : one(b)+m) :
(m == 1 ? zero(promote_type(typeof(b),typeof(m))) : one(promote_type(typeof(b),typeof(m))))
b = oftype(m,mod(b,m))
b = oftype(m,mod(b,m)) # this also checks for divide by zero
p == 0 && return mod(one(b),m)
(m == 1 || m == -1) && return zero(m)

t = prevpow2(p)
local r::T
r = 1
Expand Down
12 changes: 12 additions & 0 deletions test/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1532,3 +1532,15 @@ for i = -10:10, p = 0:5, m = -10:10
@test mod(i^p,m) == powermod(i,p,m) == mod(big(i)^p,big(m))
end
end

# with m==1 should give 0
@test powermod(1,0,1) == 0
@test powermod(big(1),0,1) == 0
@test powermod(1,0,-1) == 0
@test powermod(big(1),0,-1) == 0
# divide by zero error
@test_throws powermod(1,0,0)
@test_throws powermod(big(1),0,0)
# negative power domain error
@test_throws powermod(1,-2,1)
@test_throws powermod(big(1),-2,1)

0 comments on commit e9087e0

Please sign in to comment.