您的位置:首页 > 编程语言

第4章_循环_编程练习4.16求整数的因子

2011-04-04 19:02 225 查看
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);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐