Skip to content

prevent unnecessary repeated squaring calculation #58720

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

Merged
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
23 changes: 17 additions & 6 deletions base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -335,11 +335,6 @@ function invmod(n::T) where {T<:BitInteger}
end

# ^ for any x supporting *
function to_power_type(x::Number)
T = promote_type(typeof(x), typeof(x*x))
convert(T, x)
end
to_power_type(x) = oftype(x*x, x)
@noinline throw_domerr_powbysq(::Any, p) = throw(DomainError(p, LazyString(
"Cannot raise an integer x to a negative power ", p, ".",
"\nConvert input to float.")))
Expand All @@ -355,12 +350,23 @@ to_power_type(x) = oftype(x*x, x)
"or write float(x)^", p, " or Rational.(x)^", p, ".")))
# The * keyword supports `*=checked_mul` for `checked_pow`
@assume_effects :terminates_locally function power_by_squaring(x_, p::Integer; mul=*)
x = to_power_type(x_)
x_squared_ = x_ * x_
x_squared_type = typeof(x_squared_)
T = if x_ isa Number
promote_type(typeof(x_), x_squared_type)
else
x_squared_type
end
x = convert(T, x_)
square_is_useful = mul === *
if p == 1
return copy(x)
elseif p == 0
return one(x)
elseif p == 2
if square_is_useful # avoid performing the same multiplication a second time when possible
return convert(T, x_squared_)
end
return mul(x, x)
elseif p < 0
isone(x) && return copy(x)
Expand All @@ -369,6 +375,11 @@ to_power_type(x) = oftype(x*x, x)
end
t = trailing_zeros(p) + 1
p >>= t
if square_is_useful # avoid performing the same multiplication a second time when possible
if (t -= 1) > 0
x = convert(T, x_squared_)
end
end
while (t -= 1) > 0
x = mul(x, x)
end
Expand Down