204. 计数质数

137 阅读1分钟

地址:leetcode-cn.com/problems/co…

class Solution {
    public int countPrimes(int n) {
        if (n < 2) {
            return 0;
        }
        boolean[] isPrim = new boolean[n];
        for (int i = 2; i * i < n; i++) {
            //质数的倍数都不是质数
            if (!isPrim[i]) {
                for (int j = i * i; j < n; j += i) {
                    isPrim[j] = true;
                }
            }
        }
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (!isPrim[i]) {
                count++;
            }
        }
        return count;
    }
}