Modular Exponentiation By Squaring
Squaring the base each step halves the exponent and multiplies the result only on set bits, keeping every intermediate value below the modulus.
Code
// binary exponentiation: square the base every step while halving the exponent
fn pow_mod(mut base: u64, mut exp: u64, modulus: u64) -> u64 {
assert!(modulus > 0, "modulus must be positive");
let mut result = 1 % modulus;
base %= modulus;
while exp > 0 {
if exp % 2 == 1 {
result = result * base % modulus;
}
base = base * base % modulus;
exp /= 2;
}
result
}
fn main() {
println!("2^10 mod 1000 = {}", pow_mod(2, 10, 1000));
// Fermat's little theorem: a^(p-1) ≡ 1 (mod p) whenever p does not divide a
println!("2^6 mod 7 = {}", pow_mod(2, 6, 7));
println!("3^200 mod 50 = {}", pow_mod(3, 200, 50));
}How it works
Structurally, expect the functions pow_mod and main and nothing else.
The loop while exp > 0 is the only repeated construct.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
The entry-point signature is fn pow_mod(mut base: u64, mut exp: u64, modulus: u64) -> u64
The demo prints (2^10 mod 1000 =, 2^6 mod 7 =, 3^200 mod 50 =) as labels, so the operation behind any line is a glance away.
main is the driver: it invokes pow_mod before returning.
Key statements
assert!(modulus > 0, "modulus must be positive");
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- What does Modular Exponentiation By Squaring print when run?
- Running the file directly is enough — expect labeled output lines such as `2^10 mod 1000 =`, `2^6 mod 7 =`, `3^200 mod 50 =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.