Luogu3846 [TJOI2007] 可爱的质数/【模板】BSGS

https://www.luogu.com.cn/problem/P3846

\(BSGS\)

\(BSGS\)可以\(O( \sqrt{p} )\)处理:

\[b^l \equiv n (mod \quad p) \]

处理方法十分常规

\[令t=\sqrt{p}+1\\ 设l=kt-m\\ 则b^{kt-m} \equiv n (mod \quad p)\\ b^{kt} \equiv nb^m (mod \quad p)\\ 预处理出 nb^m(0 \le m<t)\\ 用b^{kt} \mod p去匹配(map或Hash表)\\ \]

\(Code:\)

#include<iostream>
#include<cstdio>
#include<cmath>
#include<map>
#define ll long long
using namespace std;
ll p,b,n;
map<ll,int>a;
ll ksm(ll x,ll y)
{
    ll ans=1;
    while (y)
    {
        if (y&1)
            ans=ans*x%p;
        x=x*x%p;
        y >>=1;
    }
    return ans;
}
int main()
{
    scanf("%lld%lld%lld",&p,&b,&n);
    if (n==1)
    {
        printf("0\n");
        return 0;
    }
    int g=(int)sqrt(p)+1;
    ll c=n%p;
    for (int i=0;i<g;i++)
    {
        a[c]=i+1;
        c=c*b%p;
    }
    ll y=ksm(b,g);
    ll e=1;
    for (int i=1;i<=g;i++)
    {
        e=e*y%p;
        if (a.find(e)!=a.end())
        {
            printf("%lld\n",(ll)i*g-(ll)(a[e]-1));
            return 0;
        }
    }
    puts("no solution");
    return 0;
}
posted @ 2020-07-22 19:04  GK0328  阅读(101)  评论(0编辑  收藏  举报