Skip to content

Added powm (power modulo) to the std::num module. #11735

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

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
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
31 changes: 31 additions & 0 deletions src/libstd/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,28 @@ pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
}
}

/// Raises a value to the power of p modulo d, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use std::num;
///
/// assert_eq!(num::powm(2, 4, 3), 1);
/// ```
#[inline]
pub fn powm<T: One + Mul<T, T> + Rem<T, T>>(a: T, mut p: uint, d: T) -> T {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be good to have an explicit check for d == 0, to make the error messages nicer.

let mut r: T = One::one();
let mut n: T = a % d;
while p > 0 {
if (p & 1) == 1 {
r = r * n % d;
}
n = n * n % d;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do these associate correctly? (Maybe better to write as (r * n) % d and (n * n) % d just to be clear?)

p = p >> 1;
}
r
}
/// Raise a number to a power.
///
/// # Example
Expand Down Expand Up @@ -1670,6 +1692,15 @@ mod tests {
assert_pow!((8.5, 5 ) => 44370.53125);
assert_pow!((2u64, 50) => 1125899906842624);
}

#[test]
fn test_powm() {
assert_eq!(4, powm(3, 2, 5));
assert_eq!(4, powm(2, 10, 10));
assert_eq!(1, powm(3, 16, 2));
assert_eq!(2, powm(2, 3, 3));
assert_eq!(1, powm(2, 64, 3));
}
}


Expand Down