Skip to content

Commit

Permalink
fix overflow bug in prevpow (JuliaLang#43410)
Browse files Browse the repository at this point in the history
  • Loading branch information
oscardssmith authored and LilithHafner committed Feb 22, 2022
1 parent 9eb8c16 commit 8207530
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
11 changes: 8 additions & 3 deletions base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -490,14 +490,19 @@ julia> prevpow(4, 16)
16
```
"""
function prevpow(a::Real, x::Real)
function prevpow(a::T, x::Real) where T <: Real
x < 1 && throw(DomainError(x, "`x` must be ≥ 1."))
# See comment in nextpos() for a == special case.
a == 2 && isa(x, Integer) && return _prevpow2(x)
a <= 1 && throw(DomainError(a, "`a` must be greater than 1."))
n = floor(Integer,log(a, x))
p = a^(n+1)
p <= x ? p : a^n
p = a^n
if a isa Integer
wp, overflow = mul_with_overflow(a, p)
return (wp <= x && !overflow) ? wp : p
end
wp = p*a
return wp <= x ? wp : p
end

## ndigits (number of digits) in base 10 ##
Expand Down
3 changes: 3 additions & 0 deletions test/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,9 @@ end
@test prevpow(2, 3) == 2
@test prevpow(2, 4) == 4
@test prevpow(2, 5) == 4
@test prevpow(Int64(10), Int64(1234567890123456789)) === Int64(1000000000000000000)
@test prevpow(10, 101.0) === 100
@test prevpow(10.0, 101) === 100.0
@test_throws DomainError prevpow(0, 3)
@test_throws DomainError prevpow(0, 3)
end
Expand Down

0 comments on commit 8207530

Please sign in to comment.