1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

xをn乗した数をmで割った余りを求める

Last updated at Posted at 2021-02-21

使いどころ

  • b進数で表したときの下n桁を求める

単純版 O(n)

int mod_pow(int x, int n, int m){
    int r = 1;
    while(n--){
        r *= x;
        r %= m;
    }
    return r;
}

高速版 O(logn)

#include <bitset>

int mod_pow(int x, int n, int m){
    int r = 1;
    bitset<64> bs(n);
    for(int i = 0; i < 64; i++){
        x %= m;
        if(bs[i]) r = (r * x)%m; 
        x *= x;
    }
    return r;
}
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?