hdu 1211 RSA(逆元)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w144215160044/article/details/51525283

http://acm.hdu.edu.cn/showproblem.php?pid=1211

Problem Description
RSA is one of the most powerful methods to encrypt data. The RSA algorithm is described as follow:

> choose two large prime integer p, q
> calculate n = p × q, calculate F(n) = (p - 1) × (q - 1)
> choose an integer e(1 < e < F(n)), making gcd(e, F(n)) = 1, e will be the public key
> calculate d, making d × e mod F(n) = 1 mod F(n), and d will be the private key

You can encrypt data with this method :

C = E(m) = m e mod n

When you want to decrypt data, use this method :

M = D(c) = c d mod n

Here, c is an integer ASCII value of a letter of cryptograph and m is an integer ASCII value of a letter of plain text.

Now given p, q, e and some cryptograph, your task is to "translate" the cryptograph into plain text.
 

Input
Each case will begin with four integers p, q, e, l followed by a line of cryptograph. The integers p, q, e, l will be in the range of 32-bit integer. The cryptograph consists of l integers separated by blanks. 
 

Output
For each case, output the plain text in a single line. You may assume that the correct result of plain text are visual ASCII letters, you should output them as visualable letters with no blank between them.
 

Sample Input
 
  
101 103 7 11 7716 7746 7497 126 8486 4708 7746 623 7298 7357 3239
 

Sample Output
 
  
I-LOVE-ACM.
 

题意:

输入 p, q, e, l,l代表有l个shu

①求n = p*q

②F(n)  = (p-1) * (q-1)

③gcd(e, F(n)) = 1

④选择一个d使得d * e mod F(n) = 1 mod F(n) (d即为e关于F(n)的逆元,由扩展欧几里得可得)

M = D(c) = cd mod n即为解码公式

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <stack>
#include <vector>
#include <map>

using namespace std;

#define N 2100
#define INF 0xfffffff
#define PI acos (-1.0)
#define EPS 1e-8
#define met(a, b) memset (a, b, sizeof (a))

typedef long long LL;

void ex_gcd (LL a, LL b, LL res, LL &x, LL &y)
{
    if (b==0)
    {
        x = 1;
        y = 0;
        res = a;
    }

    else
    {
        ex_gcd (b, a%b, res, y, x);
        y -= a/b*x;
    }
}

LL Quick_Pow (LL m, LL n, LL q)
{
    LL b = 1;
    while (n)
    {
        if (n&1)
            b = b * m % q;
        n >>= 1;
        m = m*m%q;
    }
    return b;
}

int main ()
{
    LL p, q, e, l, res;

    while (scanf ("%I64d %I64d %I64d %I64d", &p, &q, &e, &l) != EOF)
    {
        LL n = p * q;
        LL fn = (p-1) * (q-1);

        LL x, y;
        ex_gcd (e, fn, res, x, y);///x为e关于fn的逆元
        x = (x%fn + fn) % fn;

        while (l--)
        {
            LL c;
            scanf ("%I64d", &c);
            printf ("%c", Quick_Pow(c, x, n));
        }
        puts ("");
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/w144215160044/article/details/51525283