aboutsummaryrefslogtreecommitdiff
path: root/challenge-013/paulo-custodio/c/ch-2.c
blob: 1cf93500afd50eb6eac5387ee0c93dfde0e5a581 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
Challenge 013

Challenge #2
Write a script to demonstrate Mutually Recursive methods. Two methods are
mutually recursive if the first method calls the second and the second calls
first in turn. Using the mutually recursive methods, generate Hofstadter
Female and Male sequences.

 F ( 0 ) = 1   ;   M ( 0 ) = 0
 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0
 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0.
*/

#include <stdio.h>
#include <stdlib.h>

int M(int n);

int F(int n) {
    if (n == 0) return 1;
    return n - M( F(n - 1) );
}

int M(int n) {
    if (n == 0) return 0;
    return n - F( M(n - 1) );
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        fputs("usage: ch-1 N", stderr);
        return EXIT_FAILURE;
    }

    int N = atoi(argv[1]);
    const char* sep = "";
    printf("F: ");
    for (int n = 0; n < N; n++) {
        printf("%s%d", sep, F(n));
        sep = ", ";
    }
    printf(", ...\n");

    sep = "";
    printf("M: ");
    for (int n = 0; n < N; n++) {
        printf("%s%d", sep, M(n));
        sep = ", ";
    }
    printf(", ...\n");
}