luogu P1226 【模板】快速幂||取余运算

题解

快速幂模版题。
看了一下很好理解,就是把幂 化成 二进制 逐位累乘。
见实例:
2^11 = 2^(1011) = 2^(8+2+1) = 2^8 * 2^2 * 2^1


Code

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

int n,m,ans=0;

int main(){

    long ans,b,p,k,b1,p1;
    cin >>b>>p>>k;
    b1 = b, p1=p;

    ans =1;
    b%=k;
    while(p!=0){
        if(p&1){
            ans*=b;
            ans%=k;
        }

        b*=b;
        b%=k;
        p>>=1;
    }

    cout<<b1<<"^"<<p1<<" mod "<<k<<"="<<ans%k<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/smmyy022/article/details/81508344
今日推荐