所以我需要在每一行中摆脱这个最终的乘法符号。我尝试了几种不同的方式,但他们只是弄乱了我的代码或者没有工作,而我似乎无法解决这个问题。
以下是输出示例:
Starting value (at least 2):
59
Ending value (at least 2):
64
59 = 59 x
60 = 2 x 2 x 3 x 5 x
61 = 61 x
62 = 2 x 31 x
63 = 3 x 3 x 7 x
64 = 2 x 2 x 2 x 2 x 2 x 2 x
以下是我希望它的外观:
Starting value (at least 2):
59
Ending value (at least 2):
64
59 = 59
60 = 2 x 2 x 3 x 5
61 = 61
62 = 2 x 31
63 = 3 x 3 x 7
64 = 2 x 2 x 2 x 2 x 2 x 2
以下是代码:
import java.util.Scanner;
public class PrimeFact {
public static void main(String[] args) {
int start, stop;
int number = 0;
Scanner input = new Scanner(System.in);
System.out.println("Starting value (at least 2): ");
start = input.nextInt();
System.out.println("Ending value (at least 2): ");
stop = input.nextInt();
// stops the program if the user entered n input that cannot be factored
if (start < 2 || stop < 2) {
System.out.println("Amount must be at least 2 rather than " + start + " and " + stop + ". Quitting.");
System.exit(0);
} // end if
// loop
// calls factors
for (int i = start; i <= stop; i++) {
number = i;
printFactors(i);
System.out.println();
} // ends loop
}// ends main
// prints prime factors
public static void printFactors(int number) {
int out = number;
int count = 0;
System.out.print(out + " = ");
for (int factor = 2; factor <= number; factor++) {
int exponent = 0;
while (number % factor == 0) {
number /= factor;
exponent++;
count++;
}
if (exponent > 0) {
printExponents(exponent, factor, count);
}
}
}
//prints the factors the required number of times
public static void printExponents(int exponent, int factor, int count) {
for (int q = 1; q <= exponent; q++) {
System.out.print(factor + " x ");
// if (q /= count) {
// System.out.print(factor);
// }
}
}
}// ends class
答案 0 :(得分:0)
进入printFactors附近的ints声明添加
boolean hadFactor = false;
还修改你的电话:
if (exponent > 0) {
printExponents(exponent, factor, count, hadFactor);
hadFactor=true;
}
并在printExponents中执行
public static void printExponents(int exponent, int factor, int count, boolean hadFactor) {
for (int q = 1; q <= exponent; q++) {
if (hadFactor){System.out.print(" x ")}
System.out.print(factor);
hadFactor=true;
// if (q /= count) {
// System.out.print(factor);
// }
}