From 8207530713fd758f19da13cc2f0a96ac4a889013 Mon Sep 17 00:00:00 2001 From: Oscar Smith Date: Mon, 20 Dec 2021 11:26:30 -0500 Subject: [PATCH] fix overflow bug in prevpow (#43410) --- base/intfuncs.jl | 11 ++++++++--- test/intfuncs.jl | 3 +++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/base/intfuncs.jl b/base/intfuncs.jl index 29cf041cbcf7b3..3c2d9b4beec7be 100644 --- a/base/intfuncs.jl +++ b/base/intfuncs.jl @@ -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 ## diff --git a/test/intfuncs.jl b/test/intfuncs.jl index 0814229a5d41b5..4fc21c3bcf1b28 100644 --- a/test/intfuncs.jl +++ b/test/intfuncs.jl @@ -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