2015年9月17日星期四

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.
Hint:

public class Solution {
    public int countPrimes(int n) {
        boolean notPrimes[] = new boolean[n + 1];
        int res = 0;
        for (int i = 2; i < n; i++) {
            if (!notPrimes[i]) {
                res++;
                for (int j = 2; j * i < n; j++) {
                    notPrimes[i * j] = true;
                }
            }
        }
        return res;
    }
}

没有评论:

发表评论