我正在做编程挑战,我正在做3n + 1挑战。我已经完成了它的代码,它完全适合我,但在网站上它一直说我有错误的答案。我不知道为什么如果有人能给我一个理由,这将是一个很大的帮助。代码如下。
import java.util.*;
import java.io.*;
class Conjecture {
public static void main(String[] args) throws IOException {
int array[] = new int[8];
int finalCounter = 0;
int currentCounter = 0;
Scanner scanner = null;
try {
scanner = new Scanner(
new BufferedReader(new FileReader("text.txt")));
int counter = 0;
while (scanner.hasNext()) {
array[counter] = scanner.nextInt();
counter++;
}
} finally {
if (scanner != null) {
scanner.close();
System.out.println("done");
}
}
for (int loop = 0; loop < array.length; loop += 2) {
int i = array[loop];
int j = array[loop + 1];
finalCounter = 0;
for (int k = i; k < j; k++) {
int x = k;
currentCounter = 0;
while (x != 1) {
if (x % 2 == 0) {
x = x / 2;
currentCounter++;
} else if (x % 2 == 1) {
x = x * 3 + 1;
currentCounter++;
}
if (currentCounter > finalCounter) {
finalCounter = currentCounter;
}
}
}
System.out.println(i + " " + j + " " + (finalCounter + 1));
}
}
}
答案 0 :(得分:1)
您应该阅读file.txt
的输入,而不是从System.in
读取。由于problem statement没有说明测试用例的数量,因此您应该在阅读案例时处理每个案例。你的数组只有8个元素,我很确定会有更多的测试用例。