miller_rabin模板
2015-10-14 20:47
344 查看
miller_rabin素数测试法
#include <iostream> #include <cstdlib> #include <stdio.h> #include <algorithm> #include <math.h> #include <stdlib.h> #include <iomanip> #include <ctime> #define ll long long using namespace std; ll mod_mul(ll a,ll b,ll n){ ll res=0; while(b){ if(b&1)res=(res+a)%n; a=(a+a)%n; b>>=1; } return res; } ll mod_exp(ll a,ll b,ll n){ ll res=1; while(b){ if(b&1)res=mod_mul(res,a,n); a=mod_mul(a,a,n); b>>=1; } return res; } bool miller_rabin(ll n){ if(n==2||n==3||n==5||n==7||n==11)return true; if(n==1||!(n%2)||!(n%3)||!(n%5)||!(n%7)||!(n%11))return false; ll x,pre,u; int i,j,k=0; u=n-1; while(!(u&1)){ k++;u>>=1; } srand((ll)time(0)); for(i=0;i<5;i++){//5次足够AC了 x=rand()%(n-2)+2; if((x%n)==0)continue; x=mod_exp(x,u,n); pre=x; for(j=0;j<k;j++){ x=mod_mul(x,x,n); if(x==1&&pre!=1&&pre!=n-1)return false; pre=x; } if(x!=1)return false; } return true; } int main(){ ll n; while(cin>>n){ if(miller_rabin(n))puts("is prime"); else puts("is not prime"); } return 0; }
相关文章推荐
- LeetCode OJ:Remove Duplicates from Sorted List (排好序的链表去重)
- 安装 xcode 5.1.1
- PostgreSQL extend function - C example
- 图片格式中的小较真
- 初级X编程
- Communications link failure,The last packet successfully received from the server was *** millisecon
- hdu5477 A Sweet Journey
- PostgreSQL How to get upstream node conninfo from standby node
- Skew Binary
- JAVA中的finalize()方法
- centos6.5进入救援模式
- Android中的Fragment详解 ("碎片"这个翻译真是太烂了!)
- 为什么PostgreSQL查询语句也可能产生 xlog, 并且可能对buffer有write操作 ? hint bits
- IOS学习之 响应设备的横竖屏状态,旋转界面 达到横竖屏效果
- jdk环境变量配置以及作用
- Android.mk
- hibernate xml配置
- C++ 头文件cstring,string.h,string 三者的区别
- ARM裸机程序开发(十):C语言环境初始化
- 深入理解Activity1