清华大学机试 求root(N,k) 需要二刷 *数学推导下的快速幂取模

刚开始用的字符串来做,爆时间了;

 

 

采用如上推导,可以变成快速幂取模,这样一切就明了了;

还要注意,有的测试点算出了Nr=0,根据定律,只能得到N=k-1;

 

关键点:

无;

 

#include<iostream>
#include<string>
#include<vector>
using namespace std;

typedef long long ll;

int x, y, k;

ll charge(ll x, ll y, ll k) {
    ll res = 1;
    ll base = x;
    while (y != 0) {
        if (y % 2 == 1) {
            res = res * base;
            res %= k;
        }
        base *= base;
        base %= k;
        y /= 2;
    }
    return res;
}

int main() {
    while (cin >> x >> y >> k) {
        ll res = charge(x, y, k - 1);
        if (res == 0)
            cout << k - 1 << endl;
        else
            cout << res << endl;
    }
}

 

posted @ 2020-03-11 23:54  暮云林凌  阅读(226)  评论(0)    收藏  举报