C++实现的Miller-Rabin素性测试程序
来源:互联网 发布:安徽继远软件知乎 编辑:程序博客网 时间:2024/06/03 20:51
Miller-Rabin素性测试算法是概率算法,不是确定算法。然而测试的计算速度快,比较有效,被广泛使用。
另外一个值得介绍的算法是AKS算法,是三位印度人发明的,AKS是他们的姓氏首字母。ASK算法是确定算法,其时间复杂度相当于多项式的,属于可计算的算法。
代码来自Sanfoundry的C++ Program to Implement Miller Rabin Primality Test。
源程序如下:
/* * C++ Program to Implement Miller Rabin Primality Test */#include <iostream>#include <cstring>#include <cstdlib>#define ll long longusing namespace std; /* * calculates (a * b) % c taking into account that a * b might overflow */ll mulmod(ll a, ll b, ll mod){ ll x = 0,y = a % mod; while (b > 0) { if (b % 2 == 1) { x = (x + y) % mod; } y = (y * 2) % mod; b /= 2; } return x % mod;}/* * modular exponentiation */ll modulo(ll base, ll exponent, ll mod){ ll x = 1; ll y = base; while (exponent > 0) { if (exponent % 2 == 1) x = (x * y) % mod; y = (y * y) % mod; exponent = exponent / 2; } return x % mod;} /* * Miller-Rabin primality test, iteration signifies the accuracy */bool Miller(ll p,int iteration){ if (p < 2) { return false; } if (p != 2 && p % 2==0) { return false; } ll s = p - 1; while (s % 2 == 0) { s /= 2; } for (int i = 0; i < iteration; i++) { ll a = rand() % (p - 1) + 1, temp = s; ll mod = modulo(a, temp, p); while (temp != p - 1 && mod != 1 && mod != p - 1) { mod = mulmod(mod, mod, p); temp *= 2; } if (mod != p - 1 && temp % 2 == 0) { return false; } } return true;}//Mainint main(){ int iteration = 5; ll num; cout<<"Enter integer to test primality: "; cin>>num; if (Miller(num, iteration)) cout<<num<<" is prime"<<endl; else cout<<num<<" is not prime"<<endl; return 0;}
1 0
- C++实现的Miller-Rabin素性测试程序
- Fermat素性测试, Miller-Rabin素性测试
- Miller–Rabin 素性测试
- Rabin-Miller素性测试算法
- Miller-Rabin大数素性测试
- Miller-Rabin素性测试算法详解
- 大素数判断_fermat素性测试+Miller-Rabin素性测试
- miller-rabin素性判定
- Miller-Rabin素性检测
- Nefu 120 梅森素数【miller-rabin素性测试】
- 分享一个C#的Rabin-Miller素性检验算法
- C++实现Miller-Rabin素数测试
- 素数,费马!米勒—拉宾 素性测试(Miller–Rabin primality test)
- nyist 468 Fibonacci数列(六)(Miller-Rabin算法 大数素性测试)
- 米勒罗宾素性测试(Miller–Rabin primality test)
- 大数素性测试+大数质因数分解(miller-rabin,Pollard_rho算法)
- 大素数测试的Miller-Rabin算法
- Miller - Rabin素数测试
- 郑州iOS點 - 关于升级Mac系统后cocoapods无法导入第三方的问题解决办法
- /proc
- cygwin添加类似OSX中的`open`命令
- CHttpProxyServer
- hdu1003 Max Sum
- C++实现的Miller-Rabin素性测试程序
- runtime简介和作用(上代码)
- 生活是不需要热爱的
- 记事本动态显示文本字符
- pixhawk PX4FMU和PX4IO最底层启动过程分析
- java将源代码打成source.jar
- leetcode 232. Implement Queue using Stacks
- 三种Ceph rgw前端的配置方式
- C++与opencv的一些编程和函数的使用错误总结 如何使用RGB来划分颜色