蒙特卡罗型概率算法
什么是蒙特卡罗型算法?
蒙特卡罗法也称统计模拟法、统计试验法。是把概率现象作为研究对象的数值模拟方法。是按抽样调查法求取统计值来推定未知特性量的计算方法。蒙特卡罗是摩纳哥的著名赌城,该法为表明其随机抽样的本质而命名。故适用于对离散系统进行计算仿真试验。在计算仿真中,通过构造一个和系统性能相近似的概率模型,并在数字计算机上进行随机试验,可以模拟系统的随机特性。
例题
素数测试
int powermod(int a, int p, int n) //利用费马定理,并进行二次探测
{
int result;
int x;
if(p == 0)
result = 1;
else
{
x = powermod(a,p/2,n);
result = (x*x)%n;
if(result == 1 && x!=1 && x!=n-1)//不是自身和1
composite = ture;//一定是合数
if(p%2 == 1)
result = (result*a)%n;
}
return result
}
bool is_prime(int n){
int a,result;
composite = false;
a = randomNum(2,n-1);;//生成随机数
result = powermod(a,n-1,n);
if(composite || result!=1)
return false;
else
return true;
}
主元素问题
如果一个随机数在数组中出现的次数超过n/2次,就称其为主元素。
bool mainelement(int *a,int n){
c = randomNum(0,n-1);
int T = a[c];
int sum = 0;
for(int i = 0; i < n; i++)
{
if(a[i] == T)
sum ++;
}
if(sum > n/2)
return true;
else
return false;
}