LeetCode 204 计数质数

LeetCode 204 计数质数

问题描述:
统计所有小于非负整数 n 的质数的数量。

埃氏筛:

执行用时:15 ms, 在所有 Java 提交中击败了82.19%的用户
内存消耗:38.2 MB, 在所有 Java 提交中击败了61.06%的用户

class Solution {
    public int countPrimes(int n) {
        //0~n范围内每个数是否是质数
        boolean[] notPrime = new boolean[n+1];
        int count = 0;
        //从第一个质数2开始
        for(int i=2; i<n; i++) {
            if(notPrime[i]) {
                continue;
            }
            count++;
            //对于每个i,提前标记出一系列相关的非质数
            for(long j= (long)(i)*i; j<n; j+=i) {
                notPrime[(int)j] = true;
            }
        }
        return count;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13649799.html