2015-10-16 51 views
-2

我正在嘗試編寫一個程序,它可以將輸出作爲給定數字的素數分解。但是,我的代碼作爲"2**2**2**2**2**5**7**7**11*"的輸出提供了正確的答案,但我希望它的具體輸出爲"(p1**n1)(p2**n2)...(pk**nk)"。這裏是我的代碼:JAVA中的素數因子

public class PrimeDecomp 
{ 
    public static String factors(int n) 
    { 
     String ans = ""; 
     for (int i = 2; i <= n; i++) 
     { 
      if (n % i == 0) 
      { 
       // checks if i is a divisor of num 
       ans += i + "**"; 
       // writes i in prime factorization 
       n = n/i; 
       // since it is written down, num=num/i 
       i--; 
       // just in case their are multiple factors of same number. 
       // For example, 12=2*2*3 
      } 
     } 
     return (ans.substring(0, ans.length() - 1)); 
    } 

    public static void main(String[] args) 
    { 
     System.out.println(PrimeDecomp.factors(86240)); 
    } 
} 
+0

/*公共類PrimeDecomp { \t \t公共靜態字符串因素(INT N){ \t \t \t \t String ans =「」; \t \t的for(int i = 2; I <= N;我++){ \t \t如果(N%I == 0){//檢查是否i是NUM的除數 \t \t ANS + = I +「** 「; //在素因式分解中寫入i \t \t n = n/i; //因爲它被寫下來,所以num = num/i \t \t i--; //以防萬一他們是多個相同數字的因素。例如,12 = 2 * 2 * 3 \t \t} \t \t} \t \t回報(ans.substring(0,ans.length() - 1)); } \t public static void main(String [] args){ \t \t System.out.println(PrimeDecomp.factors(86240)); \t} } */ –

+3

您可能已經注意到註釋並沒有很好地格式化代碼。你需要編輯你的問題並在那裏添加你的代碼。 – azurefrog

+2

請確保你[請正確格式化](http://stackoverflow.com/editing-help)。 – tnw

回答

0

你幾乎得到它,而不是在一個時間計算的一​​個因素,計算所有相同的因素並計數:

public static String factors(int n) 
{ 
    String ans = ""; 
    int count = 0; 
    for (int i = 2; i <= n; i++) 
    { 
     // Reset the counter 
     count = 0; 

     /* 
     * Instead of only processing on factor, we process them all and 
     * count them 
     */ 
     while (n % i == 0) 
     { 
      count++; 
      n = n/i; 
     } 

     // If we have at least processed one add it to the string 
     if (count == 1) 
     { 
      ans += "(" + i + ")"; 
     } else if (count > 0) 
     { 
      ans += "(" + i + "**" + count + ")"; 
     } 
    } 
    return ans; 
} 

既然你是經常操作字符串在一個循環中,你應該使用StringBuilder

+0

如果是時間1,只想要數字不是1,那該怎麼辦?例如:{(2 ** 5)(5 ** 1)(7 ** 2)(11 ** 1)},我希望它是{(2 ** 5)(5)(7 ** 2) (11)}。 –

+0

添加一個if else,第一個檢查count == 1,另一個count> 0。在count == 1中,您只需將該數字添加到字符串中,如ans + =「(」+ I +「)」; –