hdu 1211 RSA (扩展欧几里得算法求逆元 +快速幂)

题目链接

题意:给出p, q, e, l,令n = p * q, fn = (p-1) * (q-1)

给出l个c,计算m = D(c) = c**d** mod n,其中m为要输入的明文对应的ascii编码,d的计算方法:> calculate d, making d × e mod F(n) = 1 mod F(n), and d will be the private key。

问明文。

思路:

出题人JGShining(极光炫影)傻逼。

题意都说不清?

大小写字母一个意思?

脑袋有坑的出题人。

出题人傻逼。

出题人傻逼。

出题人傻逼。

好了。这道题需要用到扩展欧几里得算法求逆元。。。ksm(a,mod-2)的方法是基于费马小定理,必须mod为质数才可以用。扩展偶记里算法没有这个限制。

用欧几里德算法求模的逆元:

同余方程ax≡b (mod n),如果 gcd(a,n)== 1,则方程只有唯一解。

在这种情况下,如果 b== 1,同余方程就是 ax=1 (mod n ),gcd(a,n)= 1。

这时称求出的 x 为 a 的对模 n 乘法的逆元。

对于同余方程 ax= 1(mod n ), gcd(a,n)= 1 的求解就是求解方程

ax+ ny= 1,x, y 为整数。这个可用扩展欧几里德算法求出,原同余方程的唯一解就是用扩展欧几里德算法得出的 x 。

也就是gcd(a,n,x,y);

然后再(x = x%n + n)%n,得到最小的正整数x,即为a在模n意义下的逆元。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :Wed 19 Oct 2016 04:51:40 PM CST
 4File Name :code/hdu/1211.cpp
 5************************************************ */
 6#include <cstdio>
 7#include <cstring>
 8#include <iostream>
 9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <set>
13#include <map>
14#include <string>
15#include <cmath>
16#include <cstdlib>
17#include <ctime>
18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedef long long LL;
24#define pi pair < int ,int >
25#define MP make_pair
26using namespace std;
27const double eps = 1E-8;
28const int dx4[4]={1,0,0,-1};
29const int dy4[4]={0,-1,1,0};
30const int inf = 0x3f3f3f3f;
31LL p,q,e,l,d;
32LL n,fn;
33LL exgcd( LL a,LL b,LL &x,LL &y)
34{
35    if (b==0)
36    {
37	x = 1;
38	y = 0;
39	return a;
40    }
41    LL ret = exgcd(b,a%b,y,x);
42    y-=x*(a/b);
43    return ret;
44}
45LL ksm( LL a,LL b,LL k)
46{
47    LL res = 1;
48    while (b>0)
49    {
50	if (b&1) res = (res * a)%k;
51	b = b >> 1;
52	a = (a * a) % k;
53    }
54    return res;
55}
56int main()
57{
58	#ifndef  ONLINE_JUDGE 
59	freopen("code/in.txt","r",stdin);
60  #endif
61	while (~scanf("%lld %lld %lld %lld",&p,&q,&e,&l))
62	{
63	    n = p * q;
64	    fn = (p-1) * (q-1);
65	    LL tmp;
66	    exgcd(e,fn,d,tmp);
67	    d = (d%fn + fn)%fn;
68//	    printf("d:%lld\n",d);
69	    for ( int i =1 ; i <= l ; i ++)
70	    {
71		LL x;
72		scanf("%lld",&x);
73		LL val = ksm(x,d,n);
74	//	cout<<"val:"<<val<<endl;
75		printf("%c",char(val));
76	    }
77	    printf("\n");
78	}
79  #ifndef ONLINE_JUDGE  
80  fclose(stdin);
81  #endif
82    return 0;
83}