204. Count Primes

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

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

难度:easy

题目:统计小于非负整数n的所有素数。

思路:参考素数筛选法。

Runtime: 11 ms, faster than 94.69% of Java online submissions for Count Primes.
Memory Usage: 35.9 MB, less than 21.43% of Java online submissions for Count Primes.

class Solution {
    public int countPrimes(int n) {
        boolean[] notPrimes = new boolean[n];
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (!notPrimes[i]) {
                count++;
                for (int j = 2 * i; j < n; j += i) {
                    notPrimes[j] = true;
                }
            }
        }
        
        return count;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018347077
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞