扩展BSGS模板

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#define ll long long
using namespace std;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
    while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int a,b,p;
map<int,int>mp;
int power(int x,int y,int p)
{
    int ans=1;
    while (y)
    {
        if (y&1) ans=(ll)ans*x%p;
        y>>=1;x=(ll)x*x%p;
    }
    return ans;
}
int gcd(int a,int b)
{
    return (b)?gcd(b,a%b):a;
}
inline void EX_BSGS(int a,int b,int p)
{
    if (p==1){puts("0");return;}
    a%=p;b%=p;if (!a&&!b){puts("1");return;}
    if (b==1){puts("0");return;}
    if (!a){puts("No Solution");return;}
    int d,step=0,k=1;
    while ((d=gcd(a,p))!=1)
    {
        if (b%d){puts("No Solution");return;}
        step++;p/=d;b/=d;k=(ll)k*a/d%p;
        if (b==k){printf("%d\n",step);return;}
    }
    int m=ceil(sqrt(p)),t=b;mp.clear();
    for (int i=0;i<=m;i++){mp[t]=i;t=(ll)t*a%p;}
    int A=power(a,m,p);
    t=(ll)k*A%p;
    for (int i=1;i<=m;i++)
    {
        int ans=t;t=(ll)t*A%p;
        if (mp.find(ans)!=mp.end())
        {
            ans=i*m-mp[ans]+step;
            printf("%d\n",ans);
            return;
        }
    }
    puts("No Solution");
}
int main()
{
    a=read();p=read();b=read();
    for (;a+b+p;a=read(),p=read(),b=read())EX_BSGS(a,b,p);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值