2014-04-06 58 views
0

該程序基本上是使用指數進行因式分解和打印。它越來越接近正確的答案,但它繼續循環並且不在同一行上打印它們。例如,對於600應打印2^3 * 3 * 5^2,但繼續打印2^3(新行)3^1(新行)5^2,重複。使用指數的因式分解循環

更新:通過修復原來的固定重複問題,現在打印2^3 3^1 5^2,只需要現在打印正確。

import java.util.Scanner; 
class Factoring { 
    int n; 
    void setN(int u) { 
     n = u; 
    } 

    int getN() { 
     return n; 
    } 

    void factorize() { 
     int cnt; 

     for (int i = 2; i <= n; i++) { 
      cnt = 0; 
      while (n%i == 0) { 
       cnt++; 
       n /= i; 
      } 
      if (cnt == 0) 
       continue; 
      System.out.println(i + "^" + cnt); 
     } 
    } 
} 

public class Hw10 { 
    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); 
     Factoring myF = new Factoring(); 

     int u; 

     System.out.print("Enter a number(1 or less to stop)"); 
     u = in.nextInt(); 
     while (u > 1) { 
      myF.setN(u); 
      myF.factorize(); 

      System.out.print("Enter a number(1 or less to stop)"); 
      u = in.nextInt(); 
     } 
     System.out.print("bye"); 
    } 
} 

回答

1

你需要在循環中一個標誌,以確定它是否是第一個因素如

int cnt; 
    boolean isFirstFactor = true; 

    for (int i = 2; i <= n; i++) { 
     cnt = 0; 
     while (n%i == 0) { 
      cnt++; 
      n /= i; 
     } 
     if (cnt == 0) 
      continue; 
     if (isFirstFactor) 
      isFirstFactor = false; 
     else 
      System.out.print(" * "); 
     System.out.print(i + "^" + cnt); 
    }