import javax.swing.JOptionPane;
/**
* 求整数的因子
* 求出这个整数的所有素数因数
* 如:12 分解后:2 2 3
*/
public class Exercise4_16 {
public static void main(String[] args){
//此方法效率低
int j = Integer.valueOf(JOptionPane.showInputDialog("请输入一个数:"));
int temp = j;
String str = "";
for(int i = 2 ; i < temp ; i++){
if(j % i == 0){
str += i + ",";
j = j / i;
i = 1;
}
}
JOptionPane.showMessageDialog(null, temp + "的分解因数为:" + str);
//此方法效率高
int num = Integer.parseInt(JOptionPane.showInputDialog("输入一个整数:"));
String output = num + " 的所有素数因子: ";
int i = 2;
while(i < num){
if(num % i == 0){
output += i + " , ";
num /= i;
}else i++;
}
output += i;//目的是为了去掉输出中最后的逗号。如果循环条件是(i<=num)则输出结果多一个逗号。
JOptionPane.showMessageDialog(null, output);
}
}