LoginSignup
1
0

More than 3 years have passed since last update.

桁数を抑えたバイナリ法

Posted at

普通のバイナリ法

// バイナリ法
// a^n mod m
fn pow_mod(mut a: usize, mut n: usize, m: usize) -> usize {
    let mut res: usize = 1;
    while n > 0 {
        if n & 1 == 1 {
            res = res * a % m;
        }
        a = a * a % m;
        n >>= 1;
    }
    res
}

桁数を抑えたバイナリ法

桁数を底の2乗以下に抑えます

fn pow_mod2(a: usize, mut n: usize, mk: usize) -> usize {
    let mut m = a;
    let mut ans = 1;
    let mut sf = true;
    while n > 0 {
        if sf {
            sf = false;
        } else {
            m = m * m % mk;
        }
        if n & 1 == 1 {
            ans = m * ans % mk;
        }
        println!("{} {} {}", n & 1, m, ans);
        n >>= 1;
    }
    ans
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0