我的程序如下:
#include <stdio.h>
int collatz(int seed, int count) {
int next = 0;
if (seed % 2 == 0) {
next = seed / 2;
} else {
next = 3 * seed + 1;
}
count++;
if (next == 1) {
return count;
} else {
return collatz(next, count);
}
}
int main() {
int max = 0;
int index = 0;
int i;
for (i=1; i<1000000; i++) {
int current = collatz(i, 1);
if (current > max) {
max = current;
index = i;
}
}
printf("%i\n", index);
return 0;
}
我知道递归通常只会达到一定的深度。但是据我所知,我已经实现了尾递归,它应该可以停止段错误。如果我将 i 设置为 100,000,程序就会运行,这让我相信底层算法是正确的。然而,在一百万我得到:
分段错误:11
我究竟做错了什么?