leetcode 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.

 

一开始用最傻的方法做(逐个判断是否为素数),结果超过了time limit。。

tricky的做法是 用boolean标记每个数,每当遇到一个素数,就把它的所有倍数都标记为notPrime。

class Solution {
    public int countPrimes(int n) {
        boolean[] notPrime = new boolean[n+1];
        int c = 0;
        for(int i = 2; i < n; i++){
            if(notPrime[i] == false){
                c++;
                for(int j = 2; i*j < n; j++){
                    notPrime[i*j] = true;
                }
            }
        }
        return c;
    }
    
}

 

posted @ 2019-03-03 20:24  JamieLiu  阅读(89)  评论(0编辑  收藏  举报