Download code

Jump to: navigation, search

Back to Ackermann_function_(C)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

ackermann.c

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Ackermann_function_(C)?oldid=14914
14 */
15 
16 #include <stdio.h>
17 #include <stdlib.h> /* atoi() */
18 
19 static unsigned int calls;
20 
21 unsigned int naive_ackermann(unsigned int m, unsigned int n) {
22     calls++;
23     if (m == 0)
24         return n + 1;
25     else if (n == 0)
26         return naive_ackermann(m - 1, 1);
27     else
28         return naive_ackermann(m - 1, naive_ackermann(m, n - 1));
29 }
30 
31 unsigned int iterative_ackermann(unsigned int m, unsigned int n) {
32     calls++;
33     while (m != 0) {
34         if (n == 0) {
35             n = 1;
36         } else {
37             n = iterative_ackermann(m, n - 1);
38         }
39         m--;
40     }
41     return n + 1;
42 }
43 unsigned int formula_ackermann(unsigned int m, unsigned int n) {
44     calls++;
45     while(1) {
46         switch(m) {
47         case 0:  return n + 1;
48         case 1:  return n + 2;
49         case 2:  return (n << 1) + 3;
50         case 3:  return (1 << (n+3)) - 3;
51         default:
52             if (n == 0) {
53                 n = 1;
54             } else {
55                 n = formula_ackermann(m, n - 1);
56             }
57             m--;
58             break;
59         }
60     }
61 }
62 
63 int main(int argc, char* argv[]) {
64     unsigned int m, n, result;
65     m = (unsigned)atoi(argv[1]);
66     n = (unsigned)atoi(argv[2]);
67 
68     calls = 0;
69     result = naive_ackermann(m, n);
70     printf("Naive:     %u (%u calls)\n", result, calls);
71 
72     calls = 0;
73     result = iterative_ackermann(m, n);
74     printf("Iterative: %u (%u calls)\n", result, calls);
75 
76     calls = 0;
77     result = formula_ackermann(m, n);
78     printf("Formula:   %u (%u calls)\n", result, calls);
79 
80     return 0;
81 }


hijacker
hijacker
hijacker
hijacker