蒙特卡罗算法--判断素数
// 素数.cpp : 定义控制台应用程序的入口点。
//
// MonteCarlo.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include "stdafx.h"
#include"iostream"
#include<math.h>
#include<time.h>
#include<iomanip>
using namespace std;
const unsigned long maxshort=65535L;
const unsigned long multiplier=1194211693L;
const unsigned long adder=12345L;
class RandomNumber{
private:
//当前种子
unsigned long randSeed;
public:
//构造函数
RandomNumber(unsigned long s=0);
unsigned short Random(unsigned long n);
double fRandom();
};
RandomNumber::RandomNumber(unsigned long s)
{
if(s==0)
randSeed=time(0);
else
randSeed=s;
}
double RandomNumber::fRandom()
{
return Random(maxshort)/double(maxshort);
}
unsigned short RandomNumber::Random(unsigned long n)
{
randSeed=multiplier*randSeed+adder;
return (unsigned short)((randSeed>>16)%n);
}
void power(unsigned int a,unsigned int p,unsigned int n,unsigned int &result,bool &composite)
{
unsigned int x;
if(p==0) result=1;
else
{
power(a,p/2,n,x,composite);//递归计算
result=(x*x)%n;
if((result==1)&&(x!=1)&&(x!=n-1))
composite=true;
if((p%2)==1) //p是奇数
result=(result*a)%n;
}
}
bool Prime(unsigned int n)
{
//素数测试的蒙特卡罗算法
RandomNumber rnd;
unsigned int a,result;
bool composite=false;
a=rnd.Random(n-3)+2;
power(a,n-1,n,result,composite);
if(composite||(result!=1))
return false;
else
return true;
}
bool PrimeMC(unsigned int n,unsigned int k)
{
//重复调用k次Prime算法的蒙特卡罗算法
RandomNumber rnd;
unsigned int a,result;
bool composite=false;
for(int i=1;i<=k;i++)
{
a=rnd.Random(n-3)+2;
power(a,n-1,n,result,composite);
if(composite||(result!=1))
return false;
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<PrimeMC(1105,4);
int x;
cin>>x;
}