惡補數論(二) Baby-Step-Giant-Step 大步小步求離散模對數

來源:互聯網
上載者:User

標籤:質數   測試   nbsp   opera   space   code   inf   return   amp   

知識概述

好吧,我承認這是我初三寒假就聽過的知識,然而我現在早就高一了(又是寒假,只不過我已經在省選了...)

額,這是求離散模對數的一種演算法

也就是求滿足方程a^x≡b(mod p)的最小的x(其中p為質數)

考慮將x分塊?,根據歐拉定理,只需檢查x=0,1,2...p-1是否是解即可,因為a^(p-1)≡1(mod p)當x超過p-1時就開始迴圈了哦

假設塊的大小為m

先檢查前m項,a^0,a^1,a^2...a^(m-1)是否滿足要求,把ai mod p存在hash表ei裡,求出a^m的逆a^(-m)

再考慮下面的m項,a^m,a^(m+1),a^(m+2),...,a^(2m-1),若存在解,則相當於存在i使ei*a^m≡b(mod n),兩邊左乘a^(-m)得ei≡b ‘ (mod n) (b ‘ =a^(-m)*b(mod p)).這樣,只需檢查是否存在ei=b ‘ 即可

模板

做個hash表吧

未測試模板1.0

//orz PoPoQQQ#include <math.h>#define dmin(a,b) ((a)<(b)?(a):(b))int p;//p is a prime.struct Pep{    int first,second;    Pep(int _=0,int __=0) : first(_),second(__) {}    bool operator < (const Pep &other) const {        return first < other.first;    }}namespace Hash_Table{#define inf ~0U>>1#define MaxN 10010    struct Linker{        int hash,val;        Linker *next;        Linker(int _,Linker *__) : hash(_),val(inf),next(__) {}    }*fir[MaxN];    inline int &Hash(int x){        int pos=x%MaxN;        for(Linker *iter=fir[pos];iter;iter=iter->next)            if(iter->hash==x)                return iter->val;        return (fir[pos]=new Linker(x,fir[pos]))->val;    }}inline Pep exgcd(int a,int b){    if(!b)return Pep(1,0);    Pep temp=exgcd(b,a%b);    return Pep(temp.second,temp.first-x/y*temp.second);}inline int Baby_Step_Giant_Step(int A,int B){    int i,m=ceil(sqrt(p)),temp=1,D=1;    for(i=0;i<=m;i++,(temp*=A)%=p){        int &val=Hash_Table::Hash(temp);        val=dmin(val,i);        D=temp;    }    for(temp=1,i=0;i<=m;i++,(temp*=D)%=p){        int x=((exgcd(temp,p).first%p)+p)%p;        int &val=Hash_Table::Hash(x*B%p);        if(val!=inf)return i*m+val;    }    return -1;}

 

惡補數論(二) Baby-Step-Giant-Step 大步小步求離散模對數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.