我在运行“编程挑战”一书中的“3n+1 问题”时遇到问题。
我已经尝试了可以在谷歌上找到的所有 Java 解决方案(甚至是 Stack Overflow 上的解决方案),但没有一个有效,它们都报告“错误答案”。我还找到了一个可行的 C++ 解决方案,将其翻译成 Java,同样的事情:“错误答案”。
我正在使用 Programming Challenges for Java submits中的模板,我可以发誓我的算法是正确的,我能想到的唯一可能的问题是读取输入或写入输出的代码,但我想不通出去。这是我的代码,任何帮助将不胜感激:
class myStuff implements Runnable {
@Override
public void run() {
String line = Main.ReadLn(128);
while (line != null) {
process(line);
line = Main.ReadLn(128);
}
}
private void process(String line) {
String[] data = line.split("\\s+");
if (data.length == 2) {
int low = Integer.parseInt(data[0]);
int high = Integer.parseInt(data[1]);
int max = low < high ? findMax(low, high) : findMax(high, low);
System.out.println(low + " " + high + " " + max);
}
}
private int findMax(int low, int high) {
int max = Integer.MIN_VALUE;
for (int i = low; i <= high; i++) {
int length = cycleLength(i);
if (length > max)
max = length;
}
return max;
}
private int cycleLength(int i) {
long n = i;
int length = 1;
while (n > 1) {
n = ((n & 1) == 0) ? n >> 1 : 3*n + 1;
length++;
}
return length;
}
}
// java program model from www.programming-challenges.com
class Main implements Runnable {
static String ReadLn(int maxLength) { // utility function to read from
// stdin, Provided by Programming-challenges, edit for style only
byte line[] = new byte[maxLength];
int length = 0;
int input = -1;
try {
while (length < maxLength) { // Read untill maxlength
input = System.in.read();
if ((input < 0) || (input == '\n'))
break; // or untill end of line ninput
line[length++] += input;
}
if ((input < 0) && (length == 0))
return null; // eof
return new String(line, 0, length);
} catch (java.io.IOException e) {
return null;
}
}
public static void main(String args[]) { // entry point from OS
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
@Override
public void run() {
new myStuff().run();
}
}