exBSGS求条
  • 板块灌水区
  • 楼主Alea
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/10/2 10:34
  • 上次更新2023/11/2 16:37:41
查看原帖
exBSGS求条
322792
Alea楼主2023/10/2 10:34
#include <iostream>
#include <map>
#include <cmath>
using namespace std;
typedef long long lnt;
void exgcd(lnt a,lnt b,lnt &x,lnt &y,lnt &g){
    if(b==0) x=1,y=0,g=a;
    else exgcd(b,a%b,y,x,g),y-=a%b*x;
}
lnt log(lnt a,lnt b,lnt p){
    map<lnt,lnt> hsh;
    a%=p,b%=p;
    if(b==1||p==1) return 0;
    lnt d,ax=1,cnt=0,x,y;
    while(exgcd(a,p,x,y,d),d^1){
        if(b%d) return -1;
        b/=d,p/=d,cnt++;
        ax=ax*(a/d)%p;
        if(ax==b) return cnt;
    }
    exgcd(ax,p,x,y,d);
    lnt inv=(x%p+p)%p;
    b=b*inv%p;

    int t=sqrt(p),val=1;
    while(t*t<=p) t++;
    for(int i=0;i<t;i++) hsh[b*val%p]=i,val=val*a%p;
    a=val,val=1;
    if(!a) return !b?1+cnt:-1;
    for(int i=0,j;i<=t;i++){
        j=(hsh.find(val)==hsh.end()?-1:hsh[val]);
        if(~j&&i*t-j>=0) return i*t-j+cnt;
        val=val*a%p;
    }
    return -1;
}
int main(){
    lnt a,b,p;
    while(cin>>a>>p>>b&&(a!=0||b!=0||p!=0)){
        a%=p,b%=p;
        int t=log(a,b,p);
        if(t==-1) cout<<"No Solution"<<endl;
        else cout<<t<<endl;
    }
    return 0;
}
2023/10/2 10:34
加载中...