Concise and easy Java solution


  • 0
    Y
    public class Solution {
        public int countPrimes(int n) {
    
            //corner case
            if(n <= 2) {
                return 0;
            }
    
            boolean[] notPrime = new boolean[n];
            int count = 0;
           
            for (int p = 2; p < n; p++) {
                if (!notPrime[p]) {
                    count++;
                    for (int j = p ; j < n; j += p) {
                        notPrime[j] =  true;
                    }
                }
            }
            return count;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.