1. 程式人生 > >I - How many prime numbers HDU - 2138

I - How many prime numbers HDU - 2138

exc ram bool 是不是 素數 ret 測試的 AC repr

Give you a lot of positive integers, just to find out how many prime numbers there are.

Input There are a lot of cases. In each case, there is an integer N representing the number of integers to find. Each integer won’t exceed 32-bit signed integer, and each of them won’t be less than 2.Output For each case, print the number of prime numbers you have found out.Sample Input

3
2 3 4

Sample Output

2

最開始用打表篩選素數,居然超時間。然後猜想到這個測試的數據的數目可能不大,然後就改為檢測每一個數是不是素數的方法,就ac了
#include<iostream>
#include<cmath>
using namespace std;
bool fun(int num);
int main()
{
int datanum, num,ans;
while (cin >> datanum)
{
ans = 0;
while (datanum--)
{
cin >> num;
if (num == 1) continue;
if (num == 2 || fun(num)) ans++;
}
cout << ans << endl;
}
}
bool fun(int num)
{
for (int i = 2; i <= sqrt(num); i++)
{
if (num%i == 0) return false;
}
return true;
}

I - How many prime numbers HDU - 2138