Created
January 6, 2022 14:25
-
-
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.
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Modular Exponentiation