結果
| 問題 |
No.981 一般冪乗根
|
| ユーザー |
chocorusk
|
| 提出日時 | 2020-02-08 20:43:17 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
MLE
(最新)
AC
(最初)
|
| 実行時間 | - |
| コード長 | 3,106 bytes |
| コンパイル時間 | 1,392 ms |
| コンパイル使用メモリ | 118,096 KB |
| 実行使用メモリ | 610,336 KB |
| 最終ジャッジ日時 | 2024-10-09 15:28:20 |
| 合計ジャッジ時間 | 80,359 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 29 WA * 4 TLE * 4 MLE * 7 |
ソースコード
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <cassert>
#include <fstream>
#include <utility>
#include <functional>
#include <time.h>
#include <stack>
#include <array>
#define popcount __builtin_popcount
using namespace std;
typedef long long int ll;
typedef pair<ll, int> P;
ll gcd(ll a, ll b){
if(b==0) return a;
return gcd(b, a%b);
}
ll powmod(ll a, ll k, ll mod){
ll ap=a, ans=1;
while(k){
if(k&1){
ans*=ap;
ans%=mod;
}
ap=ap*ap;
ap%=mod;
k>>=1;
}
return ans;
}
ll inv(ll a, ll m){
ll b=m, x=1, y=0;
while(b>0){
ll t=a/b;
swap(a-=t*b, b);
swap(x-=t*y, y);
}
return (x%m+m)%m;
}
vector<P> fac(ll x){
vector<P> ret;
for(ll i=2; i*i<=x; i++){
if(x%i==0){
int e=0;
while(x%i==0){
x/=i;
e++;
}
ret.push_back({i, e});
}
}
if(x>1) ret.push_back({x, 1});
return ret;
}
mt19937 mt(334);
ll solve1(ll p, ll q, int e, ll a){
int s=0;
ll r=p-1;
ll qs=1;
while(r%q==0){
r/=q;
qs*=q;
s++;
}
ll qp=1;
for(int i=0; i<e; i++) qp*=q;
ll d=qp-inv(r%qp, qp);
ll t=(d*r+1)/qp;
ll at=powmod(a, t, p), inva=inv(a, p);
if(e>=s){
if(powmod(at, qp, p)!=a) return -1;
else return at;
}
uniform_int_distribution<> rnd(1, p-1);
ll rv;
while(1){
rv=powmod(rnd(mt), r, p);
if(powmod(rv, qs/q, p)!=1) break;
}
int i=0;
ll qi=1;
while(i<s-e){
bool dame=1;
for(ll j=0; j<q; j++){
if(powmod(powmod(at, qp, p)*inva%p, qs/qp/qi/q, p)==1){
dame=0;
break;
}
(at*=rv)%=p;
}
if(dame) return -1;
i++;
qi*=q;
rv=powmod(rv, q, p);
}
return at;
}
ll solve(ll p, ll k, ll a){
if(p==2 || a==1) return 1;
ll a1=a;
ll g=gcd(p-1, k);
ll c=inv(k/g%((p-1)/g), (p-1)/g);
a=powmod(a, c, p);
if(g==1){
if(powmod(a, k, p)==a1) return a;
else return -1;
}
vector<P> f=fac(g);
ll ret=1;
ll gp=1;
for(auto r:f){
ll qp=1;
for(int i=0; i<r.second; i++) qp*=r.first;
ll x=solve1(p, r.first, r.second, a);
if(x==-1) return -1;
if(gp==1){
ret=x;
gp*=qp;
continue;
}
ll s=inv(gp%qp, qp), t=(1-gp*s)/qp;
if(t>=0) ret=powmod(ret, t, p);
else ret=powmod(inv(ret, p), -t, p);
if(s>=0) x=powmod(x, s, p);
else x=powmod(inv(x, p), -s, p);
(ret*=x)%=p;
gp*=qp;
}
if(powmod(ret, k, p)!=a1) return -1;
return ret;
}
int main()
{
int t;
cin>>t;
for(int i=0; i<t; i++){
ll p, k, a;
cin>>p>>k>>a;
cout<<solve(p, k, a)<<endl;
}
return 0;
}
chocorusk