提供的程式碼雖能編譯執行,但存在嚴重邏輯錯誤:
iszhishu 方法判斷條件 x % 2 == 0 永遠只檢查能否被 2 整除,導致所有奇數誤判為質數。i <= x/2 效率低,應優化至 i * i <= x(即 √x)。public class PrimeFinder {
public static void main(String[] args) {
int count = 0;
System.out.println("101-200 之間的質數有:");
for (int i = 101; i <= 200; i++) {
if (isPrime(i)) {
System.out.printf("%d ", i);
count++;
if (count % 10 == 0) System.out.println(); // 每 10 個換行
}
}
System.out.println("\n總共 " + count + " 個質數。");
}
/**
* 判斷質數:試除法優化至 √n
*/
public static boolean isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false; // 排除偶數
for (int i = 3; i * i <= n; i += 2) { // 只檢查奇數因子
if (n % i == 0) return false;
}
return true;
}
}
101-200 之間的質數有: 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 總共 21 個質數。
IntStream.rangeClosed(101, 200).parallel().filter(PrimeFinder::isPrime)... 利用多核心加速。isPrime 只負責判斷,主程式負責輸出與統計。