快速幂加模

fast中x为底数,y为指数,c为模
如果题目数据刁钻的话,必须要在其中所有可以加模的地方加上
特别是x开始就需要模上。

#include<iostream>

using namespace std;
unsigned long long int sum ;

void fast(unsigned long long int x, unsigned long long int y, unsigned  long long int c) {
    sum = 1;
    x = x%c;
    while (y) {
        //if y is odd
        if (y & 1) sum = sum*x%c;
        y >>= 1;
        x = x*x%c;
    }
}
int main() {
    long long int x, y, c;
    while (scanf_s("%lld%lld%lld",&x,&y,&c)!=EOF) {
        fast(x, y, c);
        cout << sum << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/sc_jn/article/details/80244485
今日推荐