← 中文资源

简体中文版本

平方取模的快速幂

快速幂(binary exponentiation)每步把底数平方、指数折半,指数当前二进制位为 1 时才把底数乘入结果;中间值始终小于模数,不会溢出。

阅读英文原文

实现说明

函数 pow_mod、main是实现的聚合点。 迭代发生在 while exp > 0 内部——循环之外的语句只执行一遍。

使用要点

  • 每一步打印都带着自己的标签:2^10 mod 1000 =、2^6 mod 7 =、3^200 mod 50 =。
  • 执行文件,main 会按顺序走完 pow_mod。

常见问题

运行「平方取模的快速幂」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 2^10 mod 1000 =、2^6 mod 7 =、3^200 mod 50 = 标签标明各步骤。

主要签名是 fn pow_mod(mut base: u64, mut exp: u64, modulus: u64) -> u64

核心语句

assert!(modulus > 0, "modulus must be positive");

代码示例

// 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));
}