Skip to content

Instantly share code, notes, and snippets.

@sibu-github
Created January 6, 2022 14:25
Show Gist options
  • Save sibu-github/d48d10f3bf68182fd513461452d786ac to your computer and use it in GitHub Desktop.
Save sibu-github/d48d10f3bf68182fd513461452d786ac to your computer and use it in GitHub Desktop.
Function for Modular exponentiation. Modular exponentiation is the remainder when an integer b (the base) is raised to the power e (the exponent), and divided by a positive integer m (the modulus); that is, c = be mod m. From the definition of division, it follows that 0 ≤ c < m.
fn modPow(base: u64, exponent: u64, modulus: u64) -> u64 {
if m == 1 {
return 0;
}
let mut r = 1;
let mut pow = exponent;
let mut num = base % modulus;
loop {
if pow == 0 {
break;
}
if pow % 2 == 1 {
r = (r * num) % m;
}
num = (num * num) % m;
pow = pow >> 1;
}
r
}
@sibu-github
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment