LeetCode 204 - Count Primes

Description:

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

public int countPrimes(int n) {
    if(n < 2) return 0;
    boolean[] nums = new boolean[n];
    Arrays.fill(nums, true);
    nums[0] = nums[1] = false;
    for(int i=2; i<=Math.sqrt(n); i++) {
        if(nums[i]) {
            for(int j=i; j*i<n; j++) {
                nums[j*i] = false;
            }
        }
    }
    int cnt = 0;
    for(int i=0; i<n; i++) {
        if(nums[i]) cnt++;
    }
    return cnt;
}

 

你可能感兴趣的:(LeetCode)