hdu2138 How many prime numbers(Miller_Rabbin随机素数测试)

来源:互联网 发布:kmeans聚类算法java 编辑:程序博客网 时间:2024/05/23 01:22

给定几个数,问其中素数的个数。

由于数量很大,打表肯定过不了,所以必须用Miller_Rabbin随机素数测试的方法,下面是我的C++ Miller_Rabbin模板


#include <iostream>#include <cstdio>#include <algorithm>using namespace std;typedef long long ll;ll exp_mod(ll a,ll b,ll mod){ll res = 1;while(b){if(b & 1) res = (res * a) % mod;a = (a * a) % mod;b >>= 1;}return res;}bool Miller_Rabbin(ll n){ll a,s = (n-1) >> 2,i = 1, t = n-1;s = min(s,(ll)50);do{a = rand() % (t) + 1;if(exp_mod(a,t,n) != 1) return false;}while(i++ < s);return true;}int main(){int n,ans;ll num;while(scanf("%d",&n)!=EOF){ans = 0;for(int i = 0;i < n;i++){scanf("%I64d",&num);if(Miller_Rabbin(num))ans++;}printf("%d\n",ans);}return 0;}


原创粉丝点击