-1
所以我需要擺脫每行最後的乘法符號。我嘗試了幾種不同的方式,但他們只是搞亂了我的代碼,或者沒有工作,我似乎無法圍繞如何解決這個問題。我該如何做到這一點,因此最後的乘法符號不包含在階乘的行中?
下面是輸出的一個例子:
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
是System.out.print'(因子+(q!=指數? 「x」:「」));' –
@ElliottFrisch你試過了嗎?看起來像這樣會在2x2x3x5的第二秒後抑制x。我得到你想要做的。我想在不是第一個因素(因爲你預計第一個而不是最後一個)之前建立一個x。 –
@JeremyKahan在我自己的代碼中,我可能會使用['StringJoiner'](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html)。 –