日期:2014-05-20  浏览次数:20917 次

输入一个正整数 N,把它分解成质因子相乘的形式。 java写
我写的总是得不到想要的结果:我是fresh 请高手帮忙
以下是我的代码
public class div {
public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  System.out.println("please enter a integer number");
  int number = in.nextInt();
  StringBuffer Sb = new StringBuffer("");
  Sb = Sb.append("1x");
  for(int i = 2;i <number; i ++){
   
  while(number % i == 0){
  Sb = Sb.append(i + "x");
  number = number / i;
  }
  continue;
   
  }
   
  System.out.println(Sb.substring(0,Sb.length()-1));
   
}

}


------解决方案--------------------
for example
Java code
import java.util.*;
public class Test {
    public static void main(String[] args) throws Throwable {
        Scanner in = new Scanner(System.in);
        System.out.println("please enter a integer number");
        int number = in.nextInt();
        List<Integer> list = new ArrayList<Integer>();
        int remain = number;
        while (true) {
            boolean flag = true;
            for (int i=2; i<=(int)Math.sqrt(remain); i++) {
                if (remain%i == 0) {
                    list.add(i);
                    remain = remain / i;
                    flag = false;
                    break;
                }
            }
            if (flag) {
                list.add(remain);
                break;
            }
        }

        if (list.size() == 1) {
            System.out.printf("%d=1*%d\n", number, number);
        } else {
            StringBuilder buf = new StringBuilder();
            buf.append(list.get(0));
            for (int i=1; i<list.size(); i++) {
                buf.append("*").append(list.get(i));
            }
            System.out.printf("%d=%s\n", number, buf);
        }
    }
}