公钥密码之RSA密码算法大素数判定:Miller-Rabin判定法!

时间:2023-03-09 05:30:45
公钥密码之RSA密码算法大素数判定:Miller-Rabin判定法!

公钥密码之RSA密码算法大素数判定:Miller-Rabin判定法!

先存档再说,以后实验报告还得打印上交。

Miller-Rabin大素数判定对于学算法的人来讲不是什么难事,主要了解其原理。

先来灌输一下费马小定理:若p为素数,a是正整数且gcd(a,p)=1,则a^(p-1)%p=1。信息安全上俗称同余。本人时常将费马小定理与欧拉定理搞混淆,不过真的很类似。这里既是利用费马小定理来判定素数的。

当然了,费马小定理对于已知素数肯定是适用的,但不免存在一些伪素数也符合这个性质,所以我们需要随机数结合费马小定理来判断。Miller-Rabin算法的基本思想就是这些。

呈上代码:

#include<bits/stdc++.h>
using namespace std;
const int N=20;
bool fast_pow(int a,int b)
{
int ans=1,tmp=b-1;
while(tmp)
{
if(tmp&1) ans=ans*a%b;
a=a*a%b;
tmp>>=1;
}
return ans==1;
}
bool miller_Rabin_check(int n)
{
for(int i=1;i<N;i++)
{
int x=rand()%n;
if(__gcd(x,n)==1)
{
if(!fast_pow(x,n))
return false;
}
}
return true;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
if(n>1&&miller_Rabin_check(n)) puts("check successful!!");
else puts("check failure!!");
}
return 0;
}