MILLER_RABIN素数判定法

//MILLER_RABIN素数判定法
#include<iostream>
using namespace std;

#include<vector>
#include<cstdlib>
#include<cmath>

int MODULAR_EXPONENTIATION(int a,int b,int n)//求a^b mod n
{
	int c = 0,d = 1;
	vector<int> vb;
	while(b)
	{
		vb.push_back(b%2);
		b /= 2;
	}
	int k = vb.size()-1;
	for(int i = k;i >= 0;--i)
	{
		c *= 2;
		d = (d*d)%n;
		if(vb[i] == 1)
		{
			++c;
			d = (d*a)%n;
		}
	}
	vb.clear();
	return d;
}

bool WITNESS(int a,int n)
{
	int t = 0,u,k = n;
	--k;
	while(k%2 == 0)
	{
		k /= 2;
		++t;
	}
	u = k;
	int *x = new int[t+1];
	x[0] = MODULAR_EXPONENTIATION(a,u,n);
	for(int i = 1;i <= t;++i)
	{
		x[i] = x[i-1]*x[i-1]%n;
		if(x[i] == 1 && x[i-1] != 1 && x[i-1] != n-1)
			return true;
	}
	if(x[t] != 1) return true;
	return false;
}

bool MILLER_RABIN(int n,int s)
{
	int a;
	srand(0);
	for(int j = 1;j <= s;++j)
	{
		a = rand();
		a %= n;
		if(a < n-1) ++a;
		if(WITNESS(a,n)) return false;
	}
	return true;
}

int main()
{
        vector<int> vi;
	vi.push_back(2);
	for(int i = 3;i <= 32768;i += 2)
	{
		if(MILLER_RABIN(i,10)) vi.push_back(i);
	}

	return 0;
}

你可能感兴趣的:(算法,素数判定)