用费马小定理判断素数

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

long long modular_power(long long a, long long n, long long p)//a^m%p
{
	if (n == 0)
		return 1;
	if (n == 1)
		return a%p;
	long long temp = a*a%p;
	if (n & 1)
		return a%p*modular_power(temp, n / 2, p) % p;
	else
		return (modular_power(temp, n / 2, p)) % p;
}

int judge(long long n,long long s)//s代表次数的判定
{
	srand(time(NULL));
	long long a;
	for (int i = 0; i != s; ++i)
	{
		 a = 1 + rand() % (n - 1);
		if (modular_power(a, n - 1, n) != 1)
			return 0;
	}
	return 1;
}
//复杂度logn


int main()
{
	int x;
	while (cin >> x)
	{
		if (judge(x,4) == 1)
			cout << x << "是素数" << endl;
		else
			cout << x << "不是素数" << endl;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_36921652/article/details/79368299