[恢]hdu 2138
2011-12-26 23:30:29
地址:http://acm.hdu.edu.cn/showproblem.php?pid=2138
题意:输入n个数,问有几个是素数。
mark:它没说具体规模,开始觉得很麻烦。其实只要到sqrt(num)判断素数性质就好了。。。正规的做法是miller-rabin检测吧。
代码:
# include <stdio.h>
# include <math.h>
int isprime(int n)
{
int i, limit = sqrt(1.0*n) ;
for (i = 2 ; i <= limit ; i++)
if (n%i==0) return 0 ;
return 1 ;
}
int main ()
{
int n, num, sum ;
while (~scanf ("%d", &n))
{
sum = 0 ;
while (n--)
{
scanf ("%d", &num) ;
if (isprime(num)) sum++ ;
}
printf ("%d\n", sum) ;
}
return 0 ;
}
更新一个用米勒拉宾的代码:
# include <stdio.h> # define LL long long int pow_mod (int a, int s, int n) { long long buff = a, mul = 1 ; while (s) { if (s & 1) mul = (mul * buff) % n ; buff = (buff * buff) % n ; s >>= 1 ; } return mul; } int Miller_Rabin(int a, int n) { int r = 0, s = n - 1, j ; if ((n % a) == 0) return 0 ; while ((s & 1) == 0) s >>= 1, r++ ; LL k = pow_mod (a, s, n) ; if (k == 1) return 1 ; for (j = 0 ; j < r ;j++, k = k * k % n) if (k == n -1 ) return 1 ; return 0 ; } int IsPrime (int n) { int i, a[4] = {2,3,5} ; //2.5 * 10^13内只有一个合数 // if (n == 3215031751) return 0 ; for (i = 0 ; i < 3 ; i++) { if (n == a[i]) return 1 ; if (Miller_Rabin (a[i], n) == 0) return 0 ; } return 1 ; } //2 2047 //3 1373653 //5 25326001 //7 3215031751 int main () { int i, n ; int sum = 0 ; while (~scanf ("%d", &i)) { sum = 0 ; while (i--) { scanf ("%d", &n) ; if (IsPrime (n)) sum++ ; } printf ("%d\n", sum) ; } return 0 ; }