[英]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 ,但我不确定如何。
您需要 2 次循环:1 次遍历数组,1 次检查所有可能的除数。 我建议将主要检查分离成一个函数。 代码:
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)
看到它住在这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.