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