Problem Description
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
这里利用了素数一定满足6n+1或者6n+5进行剪枝
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
long long n, num;
long long count = 0;
while (cin>>n)
{
count = 0;
long long x = n;
while (x--)
{
cin >> num;
bool flag = false;
if (num <= 6)
{
if (num == 2|| num == 3||num==5)
{
count++;
break;
}
}
else
if ((num + 1) % 6 == 0 || (num + 5) % 6 == 0) {
for (long long i = 2; i < sqrt(num) + 1; i++)
{
if (num % i == 0 && num != i)
{
flag = true;
break;
}
}
if(flag==false)
count++;
}
}
cout << count << endl;
}
}

该程序用于计算输入的整数序列中素数的数量。对于每个大于6的数,它检查是否满足6n+1或6n+5的形式,并通过判断是否有其他数能整除来确认是否为素数。对于小于等于6的数,直接判断是否为2、3或5。最终输出素数的总数。
3万+

被折叠的 条评论
为什么被折叠?



