> For the complete documentation index, see [llms.txt](https://anand-aryan.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://anand-aryan.gitbook.io/leetcode/204.-count-primes.md).

# 204. Count Primes

Count Primes

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

Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.

## Solution <a href="#solution" id="solution"></a>

```java
public class Solution {
     public int countPrimes(int n) {
        if (n == 0) return 0;
        if (n == 1) return 0;
        if (n == 2) return 0;

        n = n-1;

        boolean[] isPrime = new boolean[n+1];
        for(int i = 2; i <= n; i ++) {
            isPrime[i] = true;
        }

        for(int i = 2; i <= Math.sqrt(n); i ++) {
            if (isPrime[i]) {
                for(int j = 2 *i; j <= n; j += i) {
                    isPrime[j] = false;
                }
            }
        }


        int result = 0;
        for(int i = 2; i <= n; i ++) {
            if (isPrime[i]) {
                result ++;
            }
        }

        return result;
    }
}
```
