第十届蓝桥杯大赛个人赛省赛(软件类) C&C++ 研究生组-RSA解密

先把p,q求出来

cpp 复制代码
#include<iostream>
#include<cmath>
using namespace std;
typedef long long ll;
int main(){
	ll n = 1001733993063167141LL, sqr = sqrt(n);
	for(ll i = 2; i <= sqr; i++){
		if(n % i == 0){
			printf("%lld ", i);
			if(i * i != n) printf("%lld ", n / i);
		}
	}
	return 0;
}

发现de % (p-1)(q-1)=1其实也就是求d的逆元,联想到用扩欧。

解密过程是快速幂的经典应用啦~

cpp 复制代码
#include<iostream>
#include<cmath>
using namespace std;
typedef __int128 ll;

ll exGcd(ll a, ll b, ll &x, ll &y){
	if(b == 0){
		x = 1;
		y = 0;
		return a;
	}
	int g = exGcd(b, a % b, x, y), temp = x;
	x = y;
	y = temp - a / b * y;
	return g;
}

ll inverse(ll a, ll b){
	ll x, y;
	ll g = exGcd(a, b, x, y);
	if(g == 1) return (x % b + b) % b;
	else return -1;
}

ll fastPow(ll a, ll b, ll m){//计算过程中会有超出long long的情况,故设置为__int128类型 
	if(b == 0) return 1;
	else if(b & 1) return a * fastPow(a, b - 1, m) % m;
	else{
		ll t = fastPow(a, b / 2, m);
		return t * t % m;
	}
}

int main(){
	ll p = 891234941LL, q = 1123984201LL, d = 212353, n = 1001733993063167141LL, e, c = 20190324LL;
	ll t = (p - 1) * (q - 1);
	e = inverse(d, t);//de % t = 1 扩欧求d的逆元 
	printf("%lld", fastPow(c, e, n));//快速幂
	return 0;
}

其中关于__int128,范围在1039。当long long顶不住时,就可以考虑用__int128老弟啦~

相关推荐
端平入洛16 小时前
delete又未完全delete
c++
祈安_21 小时前
C语言内存函数
c语言·后端
端平入洛2 天前
auto有时不auto
c++
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
czy87874753 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
蜡笔小马3 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
m0_531237173 天前
C语言-数组练习进阶
c语言·开发语言·算法
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode