LC 204. Count Primes

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
private:
    bool checkPrime(int n){
        if(n<2)
            return false;
        if(n<4)
            return true;
        if(n%2==0)
            return false;
        for(int i=3;i*i<=n;i++)
            if(n%i == 0)
                return false;
        return true;
    }
public:
    int countPrimes(int n) {
        int cnt = 0;
        if(n<2)
            return 0;
        for(int i=2;i<n;i++){
            if(checkPrime(i)){
                cnt++;
                cout << i << " ";
            }
        }
        return cnt;
    }
};


Dicussion Forum