题目链接: https://nanti.jisuanke.com/t/25087
求x^y mod p,在O(log(n))的时间内实现。
实现代码:
#include <iostream>
using namespace std;
int pw(int x, int y, int p) {
    if (!y) {
        return 1;
    }
    int res = pw(x,y/2,p)*pw(x,y/2,p)%p;
    if (y & 1) {
        res = res * x % p;
    }
    return res;
}
int main() {
    int x, y, p;
    cin >> x >> y >> p;
    cout << pw(x, y, p) << endl;
    return 0;
} 


京公网安备 11010502036488号