LeetCode-Count Primes

LiBlog發表於2016-09-14

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.

Analysis:

See hint in leetcode.

Solution:

public class Solution {
    public int countPrimes(int n) {
        if (n<=2) return 0;
        
        boolean[] marked = new boolean[n];
        
        for (int i=3;i*i<n;i+=2)
            if (!marked[i]){
                // i*i+(2*k+1)*i = i*(i+1+2k) is an even value because (i+1) is even.
                // We can skip all such number by increasing value by 2*i every time.
                for (int value = i*i;value<n;value+=2*i){
                    marked[value]=true;
                }
            }
            
        int count = 1;
        for (int i=3;i<n;i+=2)
            if (!marked[i]){
                count++;
            }
        return count;
    }
}