Skip to content

Instantly share code, notes, and snippets.

@jsanders
Last active January 4, 2016 21:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsanders/8679668 to your computer and use it in GitHub Desktop.
Save jsanders/8679668 to your computer and use it in GitHub Desktop.
Rust extra::bigint mod_exp
// Modular exponentiation by squaring
fn mod_exp(base: &BigUint, exponent: &BigUint, modulus: &BigUint) -> BigUint {
let (zero, one): (BigUint, BigUint) = (Zero::zero(), One::one());
let mut result = one.clone();
let mut baseAcc = base.clone();
let mut exponentAcc = exponent.clone();
while exponentAcc > zero {
// Accumulate current base if current exponent bit is 1
if (exponent & one) == one {
result = (result.mul(&baseAcc)).rem(modulus);
}
// Get next base by squaring
baseAcc = (baseAcc.mul(&baseAcc)).rem(modulus);
// Get next bit of exponent
exponentAcc = exponentAcc.shr(&1);
}
result
}
#[test]
fn test_mod_exp() {
let two = 2u.to_biguint().unwrap();
let three = 3u.to_biguint().unwrap();
let seven = 7u.to_biguint().unwrap();
let one: BigUint = One::one();
assert_eq!(mod_exp(&two, &three, &seven), one);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment