# LeetCode – Count Primes (Java)

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

Java Solution 1

This solution exceeds time limit.

```public int countPrimes(int n) { n = n-1;   ArrayList<Integer> primes = new ArrayList<Integer>();   if(n<=1) return 0; if(n==2) return 1; if(n==3) return 2;   primes.add(2); primes.add(3);   for(int i=4; i<=n; i++){ boolean isPrime = true; for(int p: primes){ int m = i%p; if(m==0){ isPrime = false; break; } }   if(isPrime){ primes.add(i); } }   return primes.size(); }```

Java Solution 2

This solution is the implementation of Sieve of Eratosthenes.

```public int countPrimes(int n) { if (n <= 2) return 0;   // init an array to track prime numbers boolean[] primes = new boolean[n]; for (int i = 2; i < n; i++) primes[i] = true;   for (int i = 2; i <= Math.sqrt(n - 1); i++) { // or for (int i = 2; i <= n-1; i++) { if (primes[i]) { for (int j = i + i; j < n; j += i) primes[j] = false; } }   int count = 0; for (int i = 2; i < n; i++) { if (primes[i]) count++; }   return count; }```
Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• RMFOREVER123

``` public int countPrimes(int n) { if (n <= 2) return 0; // init an array to track prime numbers boolean[] primes = new boolean[n]; for (int i = 2; i < n; i++) primes[i] = true; for (int i = 2; i <= Math.sqrt(n - 1); i++) { // or for (int i = 2; i <= n-1; i++) { if (primes[i]) { // j=i*i not i+i for (int j = i * i; j < n; j += i) primes[j] = false; } } int count = 0; for (int i = 2; i < n; i++) { if (primes[i]) count++; } return count; } ```

• Vj

We can avoid first and last for loop in above code. Refer below code,

public static void countPrimes()

{

int n = 20;

bool[] nums = new bool[n+1];

int nonPrimeCounter = 0;

for (int i = 2; i <= 7; i++)

{

if (nums[i] == false)

{

for (int j = i+i; j <= n; j = j + i)

{

if (j%i == 0)

{

if (nums[j] == false)

{

nums[j] = true;

nonPrimeCounter++;

}

}

}

}

}

int primCounter = n – nonPrimeCounter;

}