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.

RustData Integrity

Code

rustsnippet
21 lines
// 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

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 =`.