Skip to content

Instantly share code, notes, and snippets.

@retokromer
Last active April 12, 2020 12:31
Show Gist options
  • Save retokromer/d49f5a091e9ef518d419a2d6f6cfd7f0 to your computer and use it in GitHub Desktop.
Save retokromer/d49f5a091e9ef518d419a2d6f6cfd7f0 to your computer and use it in GitHub Desktop.
Ackermann function computed with stack simulation
/*
* Copyright (c) 2020 by Reto Kromer
*
* Ackermann function:
*
* A(0,n) = n+1
* A(m,0) = A(m-1,1) if m > 0
* A(m,n) = A(m-1,A(m,n-1)) if m > 0 and n > 0
*
* where m and n are non-negative integers
*
* computed with stack simulation.
*
* This C program is released under a 3-Clause BSD License and is provided
* "as is" without warranty or support of any kind.
*/
#include <stdio.h>
#include <stdlib.h>
int A(unsigned int m, unsigned int n) {
unsigned int s = 0, *M;
M = (unsigned int *)malloc(sizeof(unsigned int));
if (M == NULL) {
fprintf(stderr, "Error: malloc failed.\n");
exit(1);
}
for (;;) {
if (m == 0) {
if (s == 0) {
return ++n;
} else {
n++;
m = M[s--] - 1;
}
} else if (n == 0) {
m--;
n = 1;
} else {
M[++s] = m;
n--;
}
}
free(M);
return n;
}
int main(int argc, char* argv[]) {
unsigned int m, n;
if (argc == 3) {
m = atoi(argv[1]);
n = atoi(argv[2]);
} else {
printf("%s", "m = ");
scanf("%d", &m);
printf("%s", "n = ");
scanf("%d", &n);
}
printf("A(%d,%d) = %d\n", m, n, A(m,n));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment