「CONNECTION 3105」 Power Modulo Inverted

「CONNECTION 3105」 Power Modulo Inverted

Portal

Subject to the effect:

On demand \ (X \) equation
\ [a ^ x \ equiv b
\; (\ mathrm {mod} \; p) \] minimum natural number solution, does not guarantee \ (a, p \) coprime


If guaranteed \ (a, p \) prime, it can be used directly \ (\ texttt {BSGS} \ ) algorithm according to the present problem.

For the purposes of this question, we consider the deformation equation

Order \ (T = \ GCD (A, P) \) , there are
\ [\ frac {a} { t} a ^ {x-1} \ equiv \ frac {b} {t} \; (\ mathrm { mod} \; \ frac {p
} {t}) \] to give
\ [\ frac {a} { t} \ cdot a ^ {x-1} \ equiv b ^ { '} \; (\ mathrm {mod} \; P ^ { '}) \]
(which can be converted to the equation, it may be better understood)

Obviously, when the \ (b \; \ mathrm { mod} \; t = 0 \) where possible a solution, we only need a known recursive solution in this manner until the \ (a ^ { '}, p ^ {' } \) prime to.

Also important to note is that the solution may be the smallest natural number had been obtained during the iteration, so the need for special iteration sentence.

Each valid operation will be at least \ (P \) divided by \ (2 \) , solving \ (\ GCD \) complexity is \ (O (log_2n) \) , so the overall complexity of this iteration of \ (O (log_2 ^ 2n) \ )

Then you can solved!

Paste the code

#include<bits/stdc++.h>
using namespace std;
using ll=long long;
ll ksm(ll a,ll b,ll p){
    ll ans=1;
    for(;b;b>>=1,a=1ll*a*a%p)
        if(b&1) ans=1ll*ans*a%p;
    return ans;
}
ll gcd(ll a,ll b){
    if(!b) return a;
    return gcd(b,a%b);
}
ll bsgs(ll a,ll b,ll p){
    unordered_map<int,int> mp;
    ll tim=0,A=1;
    while(1){
        ll t=gcd(a,p);if(t==1) break;
        if(b%t) return -1;
        b/=t,p/=t,A=1ll*A*(a/t)%p;
        ++tim;
        if(b==A) {
            return tim;
        }
    }
    ll m=sqrt(p)+1;
    ll tmp=b;
    for(ll i=0;i<m;++i,tmp=1ll*tmp*a%p) mp[tmp]=i;
    tmp=ksm(a,m,p);
    ll now=1ll*A*tmp%p;
    for(ll i=1;i<=m;++i,now=1ll*now*tmp%p){
        if(mp[now]){
            if(i*m-mp[now]+tim>=0) return i*m-mp[now]+tim;
        }
    }
    return -1;
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    ll x,y,z;
    while(cin>>x>>y>>z&&(x||y||z)){
        
        ll tmp=bsgs(x,z,y);
        if(tmp==-1) cout<<"No Solution"<<'\n';
        else cout<<tmp<<'\n'; 
    }   
    return 0;
}

Guess you like

Origin www.cnblogs.com/HenryHuang-Never-Settle/p/SPOJ3105.html