[LeedCode]Count Primes素數個數

Leetcode題目:
Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

思路( Sieve of Eratosthenes方法 ):
這裏寫圖片描述

public class Solution {
    public int countPrimes(int n) {

        if(n == 0) return 0;
        boolean[] array = new boolean[n];
        for (int i = 0;i < n;i++) array[i] = true;

        array[0] = false;
        int count = 0;
        int limit = (int) Math.sqrt(n);

        for(int i = 2; i <= limit; i++) {
            if (array[i-1]) {
                for (int j = i*i; j < n; j += i) {
                    array[j - 1] = false;
                }
            }
        }
        for (int j = 2; j < n; ++j) {
            if (array[j]) ++count;
        }
        return count;
    } 
}

參考博客:http://www.cnblogs.com/grandyang/p/4462810.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章