用JAVA实现因数分解,例如81=3*3*3*3,用while语句写

解决方案 »

  1.   


    public class Test { public static String decompose(int n){
    if(n < 2&&n > 0)
    return "1*"+n;
    if(n == 0)
    return "0";
    StringBuffer str = new StringBuffer();
    int num = Math.abs(n);
    if(n < 0)
    str.append("-");
    int i = 2;
    while(num>1){
    if(num == Test.t(num)){
    if(str.length()==0){
    str.append("1*"+num);
    }else{
    str.append(num);
    }
    break;
    }else{
    str.append(Test.t(num)+"*");
    num = num/Test.t(num);
    }
    }
    return str.toString();
    }


    public static int t(int num){
    int n = (int)Math.sqrt(num);
    int i = 2;
    while(i <= n){
    if(num%i==0)
    return i;
    i++;
    }
    return num;
    }

    public static void main(String[] args) {
    System.out.println(Test.decompose(-6));
    }
    }
      

  2.   

    public class TestYSFJ {
    int b = 0;
    int c = 0; public static void main(String[] args) {
    TestYSFJ t = new TestYSFJ();
    t.DD(-888);
    if (t.c > 0) {
    System.out.print(t.c);
    } else {
    System.out.print("(" + t.c + ")");
    } } public int DD(int a) {
    b = Math.abs((int) Math.sqrt(Math.abs(a)));
    for (int i = 2; i <= b; i++) {
    if (a % i == 0) {
    c = a / i;
    System.out.print(i + "*");
    DD(c);
    return c;
    } }
    return c; }}
      

  3.   


    while循环public class TestYSFJ {
    int b = 0;
    int c = 0; public static void main(String[] args) {
    TestYSFJ t = new TestYSFJ();
    t.DD(-888);
    if (t.c > 0) {
    System.out.print(t.c);
    } else {
    System.out.print("(" + t.c + ")");
    } } public int DD(int a) {
    b = Math.abs((int) Math.sqrt(Math.abs(a)));
    int i = 2;
    while( i <= b) {
    if (a % i == 0) {
    c = a / i;
    System.out.print(i + "*");

    DD(c);

    return c;
    }
    i++;
    }
    return c; }}