题意: 给定n
, g
求
g∑d|nC(n,d)modp
1. 质因数分解可得p是质数, 用费马小定理转成求:
∑d|nC(n,d)mod(p−1)
2. 枚举n的约数, 考虑用Lucas定理求C(n,d) % (p - 1)
3. p - 1是大合数, 把它质因数分解得到四个质数, 设为p i,用Lucas定理求 ∑d|nC(n,d)mod(pi) , 注意到最大的质数35617还是很大, 所以用乘法逆元
4. 中国剩余定理求
∑d|nC(n,d)mod(p−1)
5. 快速幂求解
6. 特判g % p == 0的情况
code
/**************************************************************
Problem: 1951
User: adrui
Language: C++
Result: Accepted
Time:124 ms
Memory:2416 kb
****************************************************************/
#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
#define left Left
const ll p = 999911659;
ll mod[] = {2, 3, 4679, 35617}, left[4];
ll fac[36000][4];/**存n!%pi*/
ll n, g;
void getFac(){/**预处理*/
fac[0][0] = fac[0][1] = fac[0][2] = fac[0][3] = 1;
for(int i = 1; i < 36000; ++i)
for(int j = 0; j < 4; ++j)
fac[i][j] = fac[i - 1][j] * i % mod[j];
}
ll FastPowMod(ll a, ll b, ll p){
ll res = 1;
while(b){
if(b & 1) res = res * a % p;
a = a * a % p;
b >>= 1;
}
return res;
}
ll Lucas(ll n, ll k, ll p, int id){
ll res = 1;
while(n && k){
ll a = n % p, b = k % p;
if(a < b) return 0;
res = res * fac[a][id] * FastPowMod(fac[b][id] * fac[a - b][id] % p, p - 2, p) % p;/**乘法逆元*/
n /= p;
k /= p;
}
return res;
}
void cal(ll x){
for(int i = 0; i < 4; ++i) left[i] = (left[i] + Lucas(n, x, mod[i], i)) % mod[i];/**C(n, d) % mod[i]*/
}
void extend_gcd(ll a, ll b, ll &x, ll &y){
if(b == 0){
x = 1;
y = 0;
return;
}
extend_gcd(b, a % b, y, x);
y -= a / b * x;
}
ll CRT(){/**中国剩余定理*/
ll res = 0, x, y;
ll M = p - 1;
for(int i = 0; i < 4; ++i){
extend_gcd(M / mod[i], mod[i], x, y);
res = ((res + x * M / mod[i] * left[i]) % M + M) % M;
}
return res;
}
int main(){
memset(left, 0, sizeof left);
getFac();
cin >> n >> g;
if(g % p == 0) cout << "0" << endl;
else{
for(ll i = 1; i * i <= n; ++i){
if(n % i) continue;
cal(i);
if(i * i != n) cal(n / i);
}
ll up = CRT();
cout << FastPowMod(g % p, up, p) << endl;
}
return 0;
}