这个程序基本上是使用指数的因素和打印。它接近正确的答案,但它继续循环,不会在同一行打印它们。例如,对于600,它应该打印2 ^ 3 * 3 * 5 ^ 2,但继续打印2 ^ 3(换行)3 ^ 1(换行)5 ^ 2,重复。
更新:通过修复sentinal来修复重复问题,现在打印2 ^ 3 3 ^ 1 5 ^ 2,现在只需要正确打印。
import java.util.Scanner;
class Factoring {
int n;
void setN(int u) {
n = u;
}
int getN() {
return n;
}
void factorize() {
int cnt;
for (int i = 2; i <= n; i++) {
cnt = 0;
while (n%i == 0) {
cnt++;
n /= i;
}
if (cnt == 0)
continue;
System.out.println(i + "^" + cnt);
}
}
}
public class Hw10 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Factoring myF = new Factoring();
int u;
System.out.print("Enter a number(1 or less to stop)");
u = in.nextInt();
while (u > 1) {
myF.setN(u);
myF.factorize();
System.out.print("Enter a number(1 or less to stop)");
u = in.nextInt();
}
System.out.print("bye");
}
}
答案 0 :(得分:1)
你需要在循环中使用一个标志来确定它是否是第一个因素,例如
int cnt;
boolean isFirstFactor = true;
for (int i = 2; i <= n; i++) {
cnt = 0;
while (n%i == 0) {
cnt++;
n /= i;
}
if (cnt == 0)
continue;
if (isFirstFactor)
isFirstFactor = false;
else
System.out.print(" * ");
System.out.print(i + "^" + cnt);
}