HDU2138 素数判定
2024-09-01 07:09:18
HDU2138 给定N个32位大于等于2的正整数 输出其中素数的个数
用Miller Rabin 素数判定法 效率很高
数学证明比较复杂,略过, 会使用这个接口即可。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long int LL;
LL getPrime(bool notprime[],LL prime[],LL N)
{
LL tot=0;
for(LL i=2;i<=N;i++)
{
if(!notprime[i]) prime[tot++]=i;
for(LL j=0;j<tot;j++)
{
if(prime[j]*i>N)break;
notprime[prime[j]*i]=true;
if(i%prime[j]==0)break;
}
}
return tot;
}
LL pow_mod(LL n,LL k,LL p)
{
if(k==0)return 1;
LL w=1;
if(k&1)w=n%p;
LL ans=pow_mod(n*n%p,k>>1,p);
return ans*w%p;
}
bool Miller_Rabin(LL n,LL a,LL d)
{
if(n==2)return true;
if(n==a)return true;
if(n%a==0)return false;
if((n&1)==0)return false;
while(!(d&1))d=d>>1;
LL t=pow_mod(a,d,n);
if(t==1)return true;//特别注意!!
while((d!=n-1)&&(t!=1)&&(t!=n-1))
{
t=(LL)t*t%n;
d=d<<1; } return (t==n-1||(d&1)==1);
}
bool isPrime(LL n,LL times)
{
if(n<2)return false;
LL a[4]={2,3,5,7};
for(LL i=0;i<4;i++){if(!Miller_Rabin(n,a[i],n-1))return false;}
return true;
}
int main()
{
LL np;
while(scanf("%lld",&np)==1)
{
LL ans=0,now;
for(LL i=0;i<np;i++)
{
scanf("%lld",&now);
if(isPrime(now,1000000))ans++;
}
printf("%lld\n",ans);
}
return 0;
}
最新文章
- ADB常用命令(Android Debug Bridge)
- ES6,Array.includes()函数的用法
- hive:框架理解
- Xcode 9.0 新增功能大全
- Swift的基础之UILabel控件
- 距离度量以及python实现(二)
- 基于用户的协同过滤电影推荐user-CF python
- 面试题:int和Integer的区别
- Dapper/SqlMapper映射对应问题
- mac上mysql root密码忘记或权限错误的解决办法
- Spring,Struts2,MyBatis,Activiti,Maven,H2,Tomcat集成(四)——Activiti集成
- Python 编程核心知识体系-模块|面向对象编程(三)
- 通过HTTP协议发送远程消息
- unity, 让主角头顶朝向等于地面法线(character align to surface normal)
- codeforces 876 C. Classroom Watch
- HDFS基本工作机制
- thinkphp 读取页面报错 说 /Runtime/Cache/Home/XXXXXX.php 错误
- Mspec
- 用 python 来操作 docx, xlsx 格式文件(一)(使用 xlsxwriter 库操作xlsx格式文件)
- Delphi xe6 android Popup控件的使用