簡體   English   中英

查找數組中素數的個數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM