【轉】[java] 第一百個素數輸出

public class HundredthPrime {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 2; ; i++) {
            for (int j = 2; j <= i; j++) {
                if (i % j == 0) {
                    if (i > j)
                        break;

                    count++;
                    break;
                }
            }
            if (count >= 100) {
                System.out.println("the hundredth prime number is: " + i);
                break;
            }
        }
    }
}

這個算法結果是對的,但可以繼續優化: j 小於 i 的平方數 就能判斷出是素數。

可參考:https://zhuanlan.zhihu.com/p/502691723

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