数论-离散对数

首先要保证底数是原根,才有求解之说呐。

介绍一种BSGS(BabyStepGiantStep)算法,正如其名,走路分大步小步,相结合正是最好的方法。

小于$\sqrt{p}$的数打表保存,然后每次迈大步就好啦~

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long i64;
const int S=1e6+7;
const int P=1e9+7;
const int M=P-1;

int bk;
int f,c;
int a;
int h[S],p[S];

int pwr(int x,int a){
    int s=1;
    while(a){
        if(a&1)
            s=(i64)s*x%P;
        x=(i64)x*x%P;
        a>>=1;
    }
    return s;
}

void psh(int t,int x){
    int k=x%S;
    while(h[k]){
        ++k;
        if(k==S)
            k=0;
    }
    h[k]=x;
    p[k]=t;
}

int fnd(int x){
    int k=x%S;
    while(h[k]&&h[k]!=x){
        ++k;
        if(k==S)
            k=0;
    }
    return h[k]?p[k]:-1;
}

void init(){
    bk=sqrt(P);
    int t=1;
    for(int i=0;i<bk;i++,t=(i64)t*c%P)
        psh(i,t);
}

int gtlog(int x){
    int t=1,p,s=pwr(c,bk);
    for(int i=0;i<P;i+=bk,t=(i64)t*s%P){
        p=fnd((i64)x*pwr(t,P-2)%P);
        if(p!=-1)
            return i+p;
    }
}

int main()
{
    scanf("%d%d",&f,&c);
    if(pwr(c,P>>1)==1||pwr(c,2)==1){
        printf("Error");
        return 0;
    }
    init();
    a=gtlog(f);
    printf("%d\n",a);
    //cout<<pwr(c,a);
    return 0;
}

 

 这里说明一下,由于上述$\frac {P-1}{2}$是一个质数,因此无需再判其它的来确定原根。严谨的判法是检验所有$k|(P-1)$,是否有$c ^ \frac{P-1}{k} \equiv 1(mod P)$,如果有,表明$c$不是原根。

转载于:https://www.cnblogs.com/l-ly-03/p/NumberTheory-DiscreteLogarithm.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值