Skip to content

Instantly share code, notes, and snippets.

@Sebbyastian
Last active April 4, 2022 21:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Sebbyastian/9bf5551f915b2694c77e to your computer and use it in GitHub Desktop.
Save Sebbyastian/9bf5551f915b2694c77e to your computer and use it in GitHub Desktop.
Ackermann function in recursive and non-recursive form
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int ack_recursive(int m, int n) {
if (m == 0) {
return n + 1;
}
if (n == 0) {
return ack_recursive(m - 1, 1);
}
return ack_recursive(m - 1, ack_recursive(m, n - 1));
}
int ack_nonrecursive(int m, int n, int *status) {
int value[n];
size_t size = 0;
for (;;) {
if (m == 0) {
n++;
if (size-- == 0) {
*status = EXIT_SUCCESS;
break;
}
m = value[size];
continue;
}
if (n == 0) {
m--;
n = 1;
continue;
}
size_t index = size++;
value[index] = m - 1;
n--;
}
return n;
}
int main(void) {
for (int m = 0; m < 2; m++) {
for (int n = 0; n < 2; n++) {
int status;
assert(ack_recursive(m, n) == ack_nonrecursive(m, n, &status) && status == EXIT_SUCCESS);
}
}
}
@meyburgh
Copy link

meyburgh commented Apr 6, 2016

thanks for sharing!

@kaspersky
Copy link

This line "int value[n];" is not correct, as you would need way larger array than size n.

@Sebbyastian
Copy link
Author

Sebbyastian commented Jan 9, 2019

This line "int value[n];" is not correct, as you would need way larger array than size n.

We can put assertions before each value access to ensure they're in range. Observe the assertions passing during runtime, thus proving that n is the correct size to use. If it weren't, we'd see an assertion failure kind of like this.

@JeongHyunho
Copy link

thanks for sharing :D

@Sampurn-Anand
Copy link

can you please explain the non-recursive version?

@Sebbyastian
Copy link
Author

Sebbyastian commented Mar 6, 2020 via email

@searsm8
Copy link

searsm8 commented Apr 4, 2022

This line "int value[n];" is not correct, as you would need way larger array than size n.

We can put assertions before each value access to ensure they're in range. Observe the assertions passing during runtime, thus proving that n is the correct size to use. If it weren't, we'd see an assertion failure kind of like this.

The only reason this array size works is because your test cases are way too small. for m and n less than 2, the function barely does anything, so it doesn't matter the size of the array. If you increased the test cases to m=3, n = 5, then the assertion fails. For larger inputs, the stack size required increases dramatically.

@Sebbyastian
Copy link
Author

Sebbyastian commented Apr 4, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment