我已经对我的代码进行了相当多次的测试,知道逻辑没有任何问题,但遗憾的是我不断遇到运行时错误。我做错了什么?
public static int cycleLength(int i, int j, int k, int count, int max) {
if(i > j)
return max;
if(k == 1) {
max = Math.max(count, max);
k = i+1;
return cycleLength(i+1, j, k, 1, max);
}
if(k %2 == 0)
return cycleLength(i, j, k/2, count+1, max);
return cycleLength(i, j, 3*k+1, count+1, max);
}
public static void main (String[] args) throws IOException {
LinkedList<Integer> list = new LinkedList<Integer>();
// reading the input and saving it into a linked list
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while(!((line = br.readLine()).isEmpty())) {
String[] tmp = line.split(" ");
list.addLast(Integer.parseInt(tmp[0]));
list.addLast(Integer.parseInt(tmp[1]));
}
// the whole thing
while(!list.isEmpty()) {
int i = list.removeFirst();
int j = list.removeFirst();
int max = cycleLength(i, j, i, 1, 1);
System.out.println(i + " " + j + " " + max);
}
}
答案 0 :(得分:0)
可能获得StackOverflowException。
由于所有计算仅在一次递归调用中完成,该调用仅在计算最后一个数字的循环长度后终止,因此堆栈将爆炸以获得更大的范围(和更大的数字),例如,对于i = 100 j = 300。
为每个要测试的数字使用一个循环,并独立计算其循环长度。因此,递归呼叫在每个号码后终止,并且不会打开&#34;直到最后一个数字范围。
这是基本的想法,而不是实际的(完整的)代码:
// read i and j
int max = -1;
for (int n = i; n <= j; n++) {
int cl = cyclelength(n); // cyclelength() may be recursive
if (cl > max) max = cl;
}
Obs:这仍然可以为更大的数字生成Stack Overflow