Last active
January 4, 2016 21:19
-
-
Save jsanders/8679668 to your computer and use it in GitHub Desktop.
Rust extra::bigint mod_exp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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