素数测试--蒙特卡罗
2015-12-11 21:10
267 查看
#include "iostream" #include "ctime" #include "cmath" #include "random.h" //自己编写的头文件 using namespace std; //Fermat: 如果n是素数,a是整数且不能被n整除,则a^(n-1) % n = 1 //二次探测:如果n是素数,x是整数且0<x<n,则 x^2 % n = 1 void power(int a, int p, int n, unsigned long &result, bool no) { unsigned long x; if(p == 0) result = 1; else { power(a, p/2, n, x, no); result = x * x % n; if(result==1 && x!=1 && x!=(n-1)) //符合费尔马小定理,但违背二次探测 no = true; //不是素数 if(p % 2 == 1) //奇数 result = result * a % n; } } bool Miller_Rebin(unsigned long n, unsigned int k) { RandomNumber rnd; bool no = false; unsigned long result; int i; for(i=2; i<=k; i++) { int a = rnd.Random(n-3) + 2; //2 ~ n-2 power(a, n-1, n, result, no); if(result!=1 || no) //不是素数 return false; } return true; } int main() { int i; for(i=10000; i<=10050; i++) if(Miller_Rebin(i, 10)) cout << i << "是素数" << endl; return 0; }
相关文章推荐
- 通过SecureCRT下载远程Linux服务器上的文件到本地Windows
- R学习随记
- 服务器端获取表单数据的编码解码问题(servlet)
- linux定时运行命令
- PHP连接MYSQL的三种方式
- POJ 1066 Treasure Hunt (判断线段相交个数)
- C语言总结
- leetcode Letter Combinations of a Phone Number
- hdu 5265 pog loves szh II
- The kth great number(优先队列)
- python笔记(模块)
- C#剪切板
- 细说MATLAB中的max函数
- 最小费用-最大流---hdu1533
- Java日志那点儿事儿
- 拷贝控制
- leetcode -- Container With Most Water -- 经典题目重要!
- 分区表 switch operation
- 模拟电路学习入门的建议(综合整理)
- Python--类-例子