Leetcode:204. Count Primes 求素數的優化問題

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.

最常見的一種代碼。

int count = 0;
        for (int i = 2; i <n; i++)
        {
            int j = 0;
            for ( j = 2; j <=Math.sqrt(i); j++)
            {
                if (i%j == 0)
                {
                    break;
                }
            }
            if (j > Math.sqrt(i))
            {
                count++;
            }

        }
        return count;

但是在測試的時候會報錯。因爲當輸入1500000的時候系統運行超時,可見需要改進。
一種改進方法如下:
時間複雜度:
時間複雜度僅有O(nloglogn)
利用厄拉多塞篩法
厄拉多塞篩法的步驟:建立從2到n的集合G={2, 3, 4, …, n},每次從集合中取出最小的數i,這個數就是質數;然後將數i*i從集合中刪除。得到一個新的集合G’,重複上述步驟直到集合爲空,就取出了所有質數。

舉例一個集合{2, 3, 4, …, 12}:

stp1:最小值爲2,取出2並刪除2,4,6,8,10,12,集合變爲{3, 5, 7, 9, 11};

stp2:最小值爲3,取出3並刪除3,6,9,集合變爲{5, 7, 11}
代碼:
別人寫的:

    if (n < 3)
            return 0;

        boolean[] f = new boolean[n];
        int count = n / 2;
        for (int i = 3; i * i < n; i += 2) {
            if (f[i])
                continue;

            for (int j = i * i; j < n; j += 2 * i) {
                if (!f[j]) {
                    --count;
                    f[j] = true;
                }
            }
        }
        return count;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章