leetcode--Count Primes

Description:

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

public class Solution {
    public int countPrimes(int n) {
        if(n<2) return 0;
		boolean[] flag = new boolean[n+1];
		int count = 0;
		for(int i=2;i<n;i++){
			if(!flag[i]){//如果是质数,则将其倍数设置为非质数
				for(int j=2;i*j<=n;j++){
					flag[i*j] = true;
				}
			}
		}
		for(int i=2;i<n;i++){
			if(!flag[i]) count++;
		}
		return count;
    }
}

你可能感兴趣的:(leetcode--Count Primes)