[LeetCode]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.

思路:

埃拉託斯特尼篩法,簡稱埃氏篩或愛氏篩,是一種由希臘數學家埃拉託斯特尼所提出的一種簡單檢定素數的算法:
要得到自然數n以內的全部素數,必須把不大於根號n的所有素數的倍數剔除,剩下的就是素數。
這裏寫圖片描述

Java代碼:

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

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