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 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
38 changes: 38 additions & 0 deletions src/libstd/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,32 @@ pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
}
}

/// Raises a value to the power of exp modulo d, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use std::num;
///
/// assert_eq!(num::powm(2, 4, 3), 1);
/// ```
#[inline]
pub fn powm<T: Zero + One + Mul<T, T> + Rem<T, T>>(mut base: T, mut exp: uint, d: T) -> T {
if d.is_zero() { fail!("modulo by zero!"); }
else if exp == 1 { base }
else {
let mut r: T = One::one();
base = base % d;
while exp > 0 {
if (exp & 1) == 1 {
r = (r * base) % d;
}
base = (base * base) % d;
exp = exp >> 1;
}
r
}
}
/// Raise a number to a power.
///
/// # Example
Expand Down Expand Up @@ -1670,6 +1696,18 @@ 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));
assert_eq!(7218, powm(1200, 3, 10001));
assert_eq!(1711, powm(999, 1980, 2014));
assert_eq!(765432099, powm(123456789, 987654, 999999999));
}
}


Expand Down