快速幂(取余) c++

题意:求a的b次幂对p取余的结果

快速幂做法:

#include<iostream>
using namespace std;
int main()
{
    long long a,b,p;
    cin>>a>>b>>p;
    long long ans = 1 % p;     //排除特殊情况,a ^ 0 % 1 = 0(b = 0 , p = 1);
    while(b){
        if(b%2) ans = (ans * a) % p;
        a = a * a % p;
        b /= 2;
    }

    cout<<ans<<endl;
    return 0;
}

                                                                                                                                                                 注:林泽吟是个小仙女

猜你喜欢

转载自blog.csdn.net/weixin_41988889/article/details/86724217