Created
September 21, 2014 12:14
-
-
Save oHaiyang/f9c5cc63aa049daaf664 to your computer and use it in GitHub Desktop.
A implement of Ackermann function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#define MAXSIZE 50000 | |
struct stack { | |
int top; | |
int m[MAXSIZE]; | |
int n[MAXSIZE]; | |
int s[MAXSIZE]; | |
int tag[MAXSIZE]; | |
} S; | |
/* Initialize a Stack from a Array */ | |
int init_stack(void) | |
{ | |
S.top = -1; | |
return 0; | |
} | |
/* Push to Stack */ | |
int push(int m, int n, int s, int tag) | |
{ | |
if (S.top != MAXSIZE) { | |
S.top++; | |
S.m[S.top] = m; | |
S.n[S.top] = n; | |
S.s[S.top] = s; | |
S.tag[S.top] = tag; | |
return 0; | |
} else | |
return 1; | |
} | |
/* Pop from Stack */ | |
int pop(int *m, int *n, int *s, int *tag) | |
{ | |
if (S.top != -1) { | |
*m = S.m[S.top]; | |
*n = S.n[S.top]; | |
*s = S.s[S.top]; | |
*tag = S.tag[S.top]; | |
S.top--; | |
return 0; | |
} else | |
return 1; | |
} | |
int is_empty() | |
{ | |
if (S.top == -1) | |
return 1; | |
else | |
return 0; | |
} | |
int is_finished() | |
{ | |
if (S.top == 0 && S.tag[S.top] == 1) | |
return 1; | |
else | |
return 0; | |
} | |
/* Only used for debugging */ | |
void print() | |
{ | |
int i = S.top; | |
for (i = S.top; i > -1; i--) | |
printf("[%d] m = %2d n = %2d s = %2d tag = %2d\n", | |
i, S.m[i], S.n[i], S.s[i], S.tag[i]); | |
} | |
/* The no-recursion way */ | |
int ack_not_recur(int mm, int nn) | |
{ | |
int m; | |
int n; | |
int s; | |
int tag; | |
int m1; | |
int n1; | |
int s1; | |
int tag1; | |
init_stack(); | |
push(mm, nn, 0, 0); | |
while (is_finished() == 0) { | |
pop(&m, &n, &s, &tag); | |
if (tag == 0) { | |
if (m == 0) { | |
push(m, n, n + 1, 1); | |
} else if (n == 0) { | |
push(m - 1, 1, 0, 0); | |
} else { | |
push(m - 1, 0, 0, 0); | |
push(m, n - 1, 0, 0); | |
} | |
} else { | |
if (is_finished() == 1) | |
break; | |
pop(&m1, &n1, &s1, &tag1); | |
if (tag1 == 0) | |
push(m1, s, 0, 0); | |
} | |
} | |
pop(&m, &n, &s, &tag); | |
return s; | |
} | |
/* The recursion way */ | |
int ack(int m, int n) | |
{ | |
if (m == 0) { | |
return n + 1; | |
} else if (m != 0 && n == 0) { | |
return ack(m - 1, 1); | |
} else { | |
return ack(m - 1, ack(m, n - 1)); | |
} | |
} | |
int main(void) | |
{ | |
printf("%d\n", ack_not_recur(3, 5)); | |
printf("%d\n", ack(3, 5)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment