2015-10-16 50 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 +“)”; –