POJ 2447 RSA 大數分解+逆元+快速冪

來源:互聯網
上載者:User

標籤:數學

連結:http://poj.org/problem?id=2447

題意:

思路:Pollard_Rho質數分解,得到兩個素數因子,P,Q,求出T,E,快速冪即可得M。

代碼:

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <map>#include <cstdlib>#include <queue>#include <stack>#include <vector>#include <ctype.h>#include <algorithm>#include <string>#include <set>#include <ctime>#define PI acos(-1.0)#define maxn 10005#define INF 0x7fffffff#define eps 1e-8#define seed 31typedef long long LL;typedef unsigned long long ULL;using namespace std;LL extend_gcd(LL a, LL b, LL &x, LL &y){    if(b==0)    {        x=1;        y=0;        return a;    }    LL r=extend_gcd(b,a%b,x,y);    LL t=x;    x=y;    y=t-a/b*y;    return r;}LL mul_mod(LL a,LL b,LL n)  {    a=a%n;    b=b%n;    LL s=0;    while(b)    {        if(b&1)            s=(s+a)%n;        a=(a<<1)%n;        b=b>>1;    }    return s;}LL pow_mod(LL a,LL b,LL n){    a=a%n;    LL s=1;    while(b)    {        if(b&1)            s=mul_mod(s,a,n);        a=mul_mod(a,a,n);        b=b>>1;    }    return s;}LL gcd(LL a,LL b){    if(a==0) return 1;    if(a<0) return gcd(-a,b);    return b==0?a:gcd(b,a%b);}LL inv(LL a,LL m){    LL d,x,y;    d=extend_gcd(a,m,x,y);    if (d==1)    {        x=(x%m+m)%m;        return x;    }    else return -1;} LL Pollard_Rho(LL n){    if(!(n&1)) return 2;    while(true)    {        LL x=(LL)rand()%n;        if(x<0)            x=-x;        LL y=x;        LL c=(LL)rand()%n;        if(x<0)            c=-c;        if(c==0||c==2) c=1;        for(int i=1,k=2;; i++)        {            x = mul_mod(x,x,n);            if (x >= c) x -= c;            else x += n - c ;            if (x == n) x = 0 ;            if (x == 0) x = n-1;            else x --;            LL d = gcd (x>y ? x-y: y-x, n);            if (d == n) break ;            if (d != 1) return d ;            if (i == k)            {                y = x;                k <<= 1 ;            }        }    }}int main(){    LL C,E,N;    while(~scanf("%lld%lld%lld",&C,&E,&N))    {        LL aa=Pollard_Rho(N);        LL T=(aa-1)*(N/aa-1);        LL D=inv(E,T);        LL M=pow_mod(C,D,N);        printf("%lld\n",M);    }    return 0;}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.