当我运行以下代码并使用gcc
编译(仅打开-std=c99
选项),然后运行可执行文件时,会出现分段错误(msg core dumped)。
这是为什么呢?
#include <stdio.h>
int count_factors(int n, int i) {
int m = n;
if (m == i) {
return 1;
} else if (m % i == 0) {
while (m % i == 0) m = m / i;
return 1 + count_factors(m, i);
} else {
return count_factors(m, i+1);
}
}
int main() {
int streak_size = 4;
int streak = 0;
int solution = 0;
int n = 2;
while (solution == 0) {
n += 1;
int c = count_factors(n, 2);
if (c == streak_size) {
streak += 1;
} else {
streak = 0;
}
if (streak == streak_size) solution = n;
}
printf("%i", solution);
return 0;
}
count_factors
中,由于您从未退出递归,因此请在count_factors
函数开头添加printf("%d %d\n", n, i);
,您就会明白了。 - Jabberwocky-Wall
。请注意,这是一般建议,可能无法帮助解决您特定的问题。 - Klas Lindbäck