Count Primes

Count the number of prime numbers less than a non-negative number, n.

Example:

Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int countPrimes(int n)
{
    bool isprime[n + 1];
    if (n <= 1)
        return 0;
    memset(isprimetruesizeof(isprime));
    for (int i = 2i * i < ni++)
    {
        if (isprime[i] == true)
        {
            for (int j = i * ij <= nj += i)
                isprime[j] = false;
        }
    }
    int cnt = 0;
    for (int i = 2i < ni++)
        if (isprime[i])
            cnt++;
    return cnt;
}

int main()
{
    int n = 10;
    cout << countPrimes(n);

    return 0;
}


No comments:

Post a Comment