[Leetcode] Count Primes 数素数

Count Primes

Description:数组

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

埃拉托斯特尼筛法 Sieve of Eratosthenes

复杂度

时间 O(NloglogN) 空间 O(N)code

思路

若是一个数是另外一个数的倍数,那这个数确定不是素数。利用这个性质,咱们能够创建一个素数数组,从2开始将素数的倍数都标注为不是素数。第一轮将四、六、8等表为非素数,而后遍历到3,发现3没有被标记为非素数,则将六、九、12等标记为非素数,一直到N为止,再数一遍素数数组中有多少素数。ip

代码

public class Solution {
    public int countPrimes(int n) {
        boolean[] prime = new boolean[n];
        Arrays.fill(prime, true);
        for(int i = 2; i < n; i++){
            if(prime[i]){
                // 将i的2倍、3倍、4倍...都标记为非素数
                for(int j = i * 2; j < n; j =  j + i){
                    prime[j] = false;
                }
            }
        }
        int count = 0;
        for(int i = 2; i < n; i++){
            if(prime[i]) count++;
        }
        return count;
    }
}
相关文章
相关标签/搜索