【数论】BSGS

1.介绍

2.Code

#include<cstdio>
#define I int
#define F(i,a,b) for(I i=a;i<=b;i++)
#define M 70921
I a,b,p,now,t,x;
struct node{I v,c;}h[M+10];
I ksm(ll x,I k){
    ll sum=1;
    while(k){
        if(k&1) sum=(sum*x)%p;
        x=(x*x)%p;k>>=1;
    }
    return sum;
}
I hash(I x){
    I k=x%M;
    while(h[k].v>=0&&h[k].v!=x) if(++k==M) k=0;
    return k;
}
I main(){
    scanf("%d %d %d",a,b,p);
    memset(h,255,sizeof h);
    m=sqrt(p);
    F(i,1,m){
        x=hash(t=1LL*t*a%p);
        h[x]=node{t,i};
    }
    now=ksm(a,m);t=1;
    F(i,1,m+1){
        x=hash(t=1LL*t*now%p);
        if(h[x].v>=0){
            printf("%d\n",i*m-h[x].c);
        }
    }
} 

猜你喜欢

转载自blog.csdn.net/zsjzliziyang/article/details/107773245