【密码学】费马小定理素性检测(C++代码实现)
作者:互联网
#include <NTL/ZZ.h>
#include<iostream>
using namespace std;
using namespace NTL;
long PrimeTest(const ZZ& n, long t)
{
if (n <= 1) return 0;
//用2000以内的素数对n进行初筛
PrimeSeq s; // 生成一个素数数列
long p;
p = s.next(); // first prime is always 2
while (p && p < 2000) {
if ((n % p) == 0) return (n == p);
p = s.next();
}
//Fermat法推演n的素性
ZZ x;
for (long i = 0; i < t; i++) {
x = RandomBnd(n); // 随机数 between 0 and n-1
if ((x,n)==1 && PowerMod(x,n-1,n)!=1)
return 0;
}
return 1;
}
int main()
{
ZZ n;
long t;
cout << "请输入Fermat待检测的n: ";
cin >> n;
cout << "请输入Fermat检测次数t:";
cin >> t;
if (PrimeTest(n, t))
cout << "n是素数\n";
else
cout << "n是合数\n";
}
标签:素性,namespace,long,PrimeTest,C++,using,include,密码学,cout 来源: https://blog.csdn.net/Mitchell_Donovan/article/details/120603183