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

Improve pow speed for expensive types by multiplying references not cloned values (reopen) #153

Closed
wants to merge 1 commit into from
Closed
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
11 changes: 7 additions & 4 deletions traits/src/pow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,24 @@ use {One, CheckedMul};
/// assert_eq!(pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T {
pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T
where
for<'a> &'a T: Mul<&'a T, Output = T>,
{
if exp == 0 { return T::one() }

while exp & 1 == 0 {
base = base.clone() * base;
base = &base * &base;
exp >>= 1;
}
if exp == 1 { return base }

let mut acc = base.clone();
while exp > 1 {
exp >>= 1;
base = base.clone() * base;
base = &base * &base;
if exp & 1 == 1 {
acc = acc * base.clone();
acc = &acc * &base;
}
}
acc
Expand Down