HDU 2138
传送门 HDU 2138
题目描述: 给你一堆数字,判断有多少个素数
应用 MillerRabin算法
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std ;
typedef long long LL ;
int mp[] = { 2 , 7 , 61 } ; // 参考一位大牛的32位的只需检测这3个数,最好还是检测从2到37的所有质数
LL qpow(LL a , LL b , LL n ) // 快速幂取模
{
LL ans = 1 ;
for( ; b > 0 ; b>>= 1 , a = a*a%n )
if( b&1 ) ans = ans*a%n ;
return ans ;
}
bool MillerRabin(LL num ) // 检测
{
if( num <= 2 )
if( num == 2 ) return true ;
else return false ;
LL u = num-1 ;
while ( u%2 == 0 ) u /= 2 ; // 去掉所有2
LL tmp = u ;
for( int i = 0 ; i < 3&&mp[i] < num ; i++ )
{
u = tmp ;
LL x = qpow( mp[i] , u , num ) ;
while ( u < num )
{
LL y = qpow( x , 2 , num ) ; // y为平方后的数,x为先前的
if( y==1 && x != 1 && x != num-1) // 二次检测
return false ;
u = u*2 ;
x = y ;
}
if(x != 1 ) // 费马小定理
return false ;
}
return true ;
}
int main( )
{
LL n , tmp , cnt ;
while ( ~scanf("%lld" , &n ) )
{
cnt = 0 ;
while ( n-- )
{
scanf("%lld" , &tmp ) ;
if( MillerRabin(tmp) )
cnt++ ;
}
printf("%lld\n" , cnt ) ;
}
return 0 ;
}