在一个数组中找到一个素数
Finding number of prime numbers in an array
我正在尝试编写一个函数,查找数组中素数的数量。
int countPrimes(int a[], int size)
{
int numberPrime = 0;
int i = 0;
for (int j = 2; j < a[i]; j++)
{
if(a[i] % j == 0)
numbPrime++;
}
return numPrime;
}
我认为我错过的是我必须在每次迭代后重新定义I,但我不确定如何。
你需要两个循环:一个遍历数组,一个检查所有可能的除数。我建议把质数检查分离成一个函数。代码:
bool primeCheck(int p) {
if (p<2) return false;
// Really slow way to check, but works
for(int d = 2; d<p; ++d) {
if (0==p%d) return false; // found a divisor
}
return true; // no divisors found
}
int countPrimes(const int *a, int size) {
int numberPrime = 0;
for (int i = 0; i < size; ++i) {
// For each element in the input array, check it,
// and increment the count if it is prime.
if(primeCheck(a[i]))
++numberPrime;
}
return numberPrime;
}
您也可以这样使用std::count_if
:
std::count_if(std::begin(input), std::end(input), primeCheck)