扩展欧拉定理
当a和p互质的时候,a^(b%f(p)) = 1 (mod p)
当a和p不互质的时候,a^(b%f(p) + f(p)) = 1 (mod p), 其中需要满足b>=f(p)
一般可以写作a^min(b, b%f(p) + f(p)) (mod p)
题目链接:http://oj.daimayuan.top/course/12/problem/535
f(p)除了2一定是偶数,所以他的下降速度是log级别的
f(p) <= p/2
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL qmi(LL a, LL b, LL mod){
LL res = 1;
while(b){
if(b&1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
int calc(int p){
if(p == 1) return 0;
int phi = p;
int q = p;
for(int i = 2; i * i <= p; i ++){
if(p % i == 0){
phi = phi / i *(i - 1);
while(p % i == 0) p /= i;
}
}
if(p != 1) phi = phi / p * (p - 1);
return qmi(2, calc(phi) + phi, q);
}
void slove(){
int p; scanf("%d", &p);
printf("%d\n", calc(p));
return ;
}
int main(){
int T; scanf("%d", &T);
while(T--){
slove();
}
return 0;
}