Why is this failing? I have written Ackermann's function in C and used longs to make sure that no number will be too small. Yet, when I go above (including) 4 for m and n, it gives me a segmentation fault: 11
. Does anyone know why?
#include <stdio.h>
int ackermann(long m, long n) {
if (m == 0)
return n + 1;
else if (m > 0 && n == 0)
return ackermann(m - 1, 1);
else if (m > 0 && n > 0)
return ackermann(m - 1, ackermann(m, n - 1));
}
int main() {
long result = ackermann(4, 4);
printf("%lu", result);
}
The size of an
unsigned long long
is 2^6 (64) bits. The size of the result forackermann(4, 2)
is greater than 2^16 (65536) bits. You can computeackermann(4, 1)
andackermann(5, 0)
but not much with larger values ofm
andn
.Code-wise, you use a signed
long
when an unsignedlong
might serve you better and you declare theackermann()
function itself to return asigned int
which is inconsistent. (Yourackermann()
function also has a fourth exit point that isn't properly defined, compiler-wise.) Here's a rework of your code usingunsigned long long
which still won't get you very far: