Java中基本素数因子化与指数

时间:2015-09-26 16:52:30

标签: java prime-factoring exponent

问题: 任何正整数都可以表示为素数的唯一乘积,也称为素数因子分解。例如: 60 = 2 ^ 2 * 3 * 5

编写一个程序来计算正整数的素数分解。

输入:单个整数n,其中n≥2。

输出:格式为“p ^ a * 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?

1 个答案:

答案 0 :(得分: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);
    }
}