bsgs算法 a^x=bmod(c) 求x (模板)

题目链接:

https://cn.vjudge.net/problem/POJ-2417

题目大意:

具体思路:

https://blog.csdn.net/clover_hxy/article/details/50683832

AC代码:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<map>
using namespace std;
# define inf 0x3f3f3f3f
# define ll long long
const int maxn = 2e5+100;
ll a,b,c,m;
map<ll,int>vis;
ll qsm(ll t1,ll t2,ll mod)
{
    ll ans=1ll;
    while(t2)
    {
        if(t2&1)
            ans=ans*t1%mod;
        t1=t1*t1%mod;
        t2>>=1;
    }
    return ans%mod;
}
int main()
{
    while(~scanf("%lld %lld %lld",&c,&a,&b))
    {
        vis.clear();
        if(a%c==0)
        {
            printf("no solution\n");
            continue;
        }
        int flag=0;
        m=ceil(sqrt(c));
        ll ans;
        for(int i=0; i<=m; i++)
        {
            if(!i)
            {
                ans=b%c;
                vis[ans]=i;
                continue;
            }
            else
            {
                ans=(ans*a)%c;
                vis[ans]=i;
            }
        }
        ll t=qsm(a,m,c);
        ans=1;
        for(int i=1; i<=m; i++)
        {
            ans=ans*t%c;
            if(vis[ans])
            {
                int tmp=i*m-vis[ans];
                printf("%d\n",(tmp%c+c)%c);
                flag=1;
                break;
            }
        }
        if(!flag)
        {
            printf("no solution\n");
        }
    }
    return 0;
}

 

posted @ 2019-06-13 21:12  Let_Life_Stop  阅读(312)  评论(0编辑  收藏  举报