輸入一個正整數 N,輸出其質因數分解式,例如 10=2*5、60=2*2*3*5。
import javax.swing.JOptionPane;
public class PrimeFactorization {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("請輸入正整數 N(輸入 exit 結束):");
if (input == null || input.equalsIgnoreCase("exit")) return;
try {
int n = Integer.parseInt(input.trim());
if (n <= 1) {
JOptionPane.showMessageDialog(null, "請輸入大於 1 的正整數");
return;
}
System.out.print(n + " = ");
factorize(n);
System.out.println();
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "輸入格式錯誤,請輸入整數");
}
}
/**
* 遞迴分解質因數,直接輸出到標準輸出
*/
private static void factorize(int n) {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
System.out.print(i + "*");
factorize(n / i);
return; // 關鍵:找到最小質因子後立即遞迴並返回,避免重複輸出
}
}
// 迴圈結束仍未 return,表示 n 本身是質數
System.out.print(n);
}
}
public static String factorizeIterative(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 2; i * i <= n; i++) {
while (n % i == 0) {
sb.append(i).append('*');
n /= i;
}
}
if (n > 1) sb.append(n);
else if (sb.length() > 0) sb.setLength(sb.length() - 1); // 移除尾端 *
return sb.toString();
}
| 特性 | 遞迴版 | 迭代版 |
|---|---|---|
| 程式碼簡潔度 | 高 | 中 |
| 堆疊風險 | 極大數可能溢位 | 無 |
| 字串組裝靈活度 | 低(直接列印) | 高(StringBuilder) |
| 除錯容易度 | 較難 | 容易 |
i <= n/2 → 效率極差,正確為 i * i <= n。return → 導致重複輸出(如 12 輸出 2*2*3*3)。若 N 超過 long 範圍,需引入 BigInteger 搭配 Pollard's Rho 演算法,單純試除法不再適用。