简体   繁体   中英

Finding number of prime numbers in an array

I'm trying to write a function that finds the 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 think what I'm missing is I have to redefine i after every iteration, but I'm not sure how.

You need 2 loops: 1 over the array, 1 checking all possible divisors. I'd suggest separating out the prime check into a function. Code:

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;
}

You can also use std::count_if like this:

std::count_if(std::begin(input), std::end(input), primeCheck)

See it live here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM