2019蓝桥杯省赛:RAS解密

题目链接:https://nanti.jisuanke.com/t/45590

题目描述:

2019蓝桥杯省赛:RAS解密_第1张图片

思路:

A组填空题里面最难的一个了吧。。说一下思路:这个题首先是要找出两个质数p,q,这个应该没啥难度,直接枚举。之后是运用拓展欧几里得算法找到e,之后再用快速幂求出原文就可以了。不过要注意,普通快速幂会爆
long long ,需要再套一个快速乘才行。

代码:

找p,q:

#include
typedef long long ll;

ll n=1001733993063167141;
ll p,q;

int main()
{
	ll i;
	int cnt=0;
	for(i=100000001;cnt<500000000;i+=2)
	{
		if(n%i==0)
		{
			p=i;
			q=n/i;
			printf("p = %lld\nq = %lld\n",p,q);
			return 0;
		}
	}
	return 0;
}

结果:

p = 891234941
q = 1123984201

找结果:

#include

typedef long long ll;
ll p = 891234941;
ll q = 1123984201;
ll n=1001733993063167141;
ll C=20190324;
ll d=212353;
ll m=(p-1)*(q-1);
ll X,e;  //找e,需要用拓展欧几里得算法和 


//拓展欧几里得算法 
ll ex_gcd(ll a,ll b,ll &x,ll &y)
{
	if(!b)
	{
		x=1;
		y=0;
		return a;
	}
	ll ans,m,n;
	ans=ex_gcd(b,a%b,x,y);
	m=y;
	n=x-a/b*y;
	x=m;
	y=n;
	return ans;
}


//乘法逆元 
ll inv(ll a,ll n)
{
	ll x,y;
	ll ans;
	ans=ex_gcd(a,n,x,y);
	if(ans!=1)
	{
		return -1;
	}
	return (x%n+n)%n;
}

//快速乘法 
ll fast_mul(ll a,ll b,ll mod)
{
	ll ans=0;
	ll base=a;
	for(;b;b>>=1)
	{
		if(b&1)
		{
			ans=ans+base;
			ans=ans%mod;
		}
		base=base*2;
		base=base%mod;
	}
	return ans;
} 

//快速幂
ll fast_power(ll a,ll n,ll mod)
{
	ll ans=1;
	ll base=a;
	for(;n;n>>=1)
	{
		if(n&1)
		{
			ans=fast_mul(ans,base,mod);
			ans=ans%mod;
		}
		base=fast_mul(base,base,mod);
		base=base%mod;
	}
	return ans;
} 


int main()
{
	e=inv(d,m);
	printf("e = %lld\n",e);
	printf("d * e mod m = %lld\n",fast_mul(d,e,m));
	X=fast_power(C,e,n);
	printf("C ^ e mod n = %lld\n",X);
	printf("X ^ d mod n = %lld\n",fast_power(X,d,n));
	return 0;
}

运行结果:

e = 823816093931522017
d * e mod m = 1
C ^ e mod n = 579706994112328949
X ^ d mod n = 20190324

你可能感兴趣的:(蓝桥杯,拓展欧几里得,乘法逆元)