2015-09-26 39 views
0

問題: 任何正整數都可以表示爲素數的唯一乘積,也稱爲素數因子分解。例如: 60 = 2^2 * 3 * 5帶有Java中指數的基本素分解

編寫一個程序來計算正整數的素因子分解。

輸入:一個整數,n,其中n≥2.

輸出:與所述格式的字符串:「P ^一個* Q^b *表...」,其中p和q是素數,a和b是指數。如果指數是1,那麼它應該被省略。

我已經得到了一切,我只需要找到一種方法將它放入「p^a * q^b * ...」窗體中。

這是我的代碼:

import java.util.Scanner; 

public class PrimeFactorization { 
public static void main(String[] args) { 

    // Input: A single integer, n, where n is greater than or equal to 2. 

    System.out.println("Please input an integer greater than or equal to two!"); 
    System.out.println("This number will be factored."); 
    Scanner inputNum = new Scanner(System.in); 
    int toBFactored = inputNum.nextInt(); 

    // If the input does not fit the requirements, ask again for an input. 

    while (toBFactored < 2) { 
      System.out.println("Please input an integer greater than or equal to two."); 
      toBFactored = inputNum.nextInt(); 
    } 

    // Output: A string with the format: "p^a * q^b * ...", where p and q are 
    // primes, and a and b are exponents. 
    // Decide first if a number (testNum) is prime. 

    int primedecider = 0; 
    for (int testNum = 2; testNum < toBFactored; testNum ++) { 
      for (int factor = 2; factor < testNum; factor ++) { 
       if (testNum % factor != 0 || testNum == 2) { 
        // Do nothing if prime. 
       } else { 
        primedecider += 1; 
        // Add if composite. 
       } 
      } 

      // If testNum is prime, if primedecider = 0, test if testNum divides 
      // evenly into toBFactored. 

      while (primedecider == 0 && toBFactored % testNum == 0 { 
       System.out.print(testNum + " "); 
       toBFactored /= testNum; 
      } 
    } 
    System.out.print(toBFactored); 

    inputNum.close(); 
} 
} 

我給120輸出爲 「2 2 2 3 5」。我如何將它變成2^3 * 3 * 5?

+0

你的問題實際上與素分解無關;你的問題是「計數列表中的重複元素」:而不是打印到'System.out',將因子存儲在一個數組中,然後檢查出這個解決方案:http://stackoverflow.com/questions/5211194/count- OCCURENCES-的詞功能於數組列表。 –

回答

0

如果不是打印的因素有System.out.println, 如果你把它們放在一個列表,然後 這些功能將他們您所描述的方式進行格式化。 這當然只是這樣做的很多方法之一。

private String formatFactors(List<Integer> factors) { 
    StringBuilder builder = new StringBuilder(); 

    int prev = factors.get(0); 
    int power = 1; 
    int factor = prev; 

    for (int i = 1; i < factors.size(); ++i) { 
     factor = factors.get(i); 
     if (factor == prev) { 
      ++power; 
     } else { 
      appendFactor(builder, prev, power); 
      prev = factor; 
      power = 1; 
     } 
    } 
    appendFactor(builder, factor, power); 

    return builder.substring(3); 
} 

private void appendFactor(StringBuilder builder, int factor, int power) { 
    builder.append(" * ").append(factor); 
    if (power > 1) { 
     builder.append("^").append(power); 
    } 
}