aboutsummaryrefslogtreecommitdiff
path: root/entries/williamvietnguyen/fibberoni.c
blob: e3c3c4d271aa0f7d0d3ea72c86b21dc8b55005d6 (plain) (blame)
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
/* fib.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int fibberoni_compute(int n, int* cache) {
    if (n < 2) {
        return n;
    }
    if (cache[n] != -1) {
        return cache[n];
    }
    cache[n] = fibberoni_compute(n - 1, cache) + fibberoni_compute(n - 2, cache);
    return cache[n];
}

int fibberoni(int n) {
    int sign, result, cache[abs(n) + 1];
    sign = (n < 0) ? -1 : 1;
    memset(cache, -1, sizeof(int) * (abs(n) + 1));
    result = fibberoni_compute(abs(n), cache);
    return sign * result;
}

void usage() {
   printf("Usage: ./fibberoni -12\n");
   exit(EXIT_FAILURE);
}

int main(int argc, char** argv) {
    int n, result;
    if (argc < 2) {
        usage();
    }
    n = atoi(argv[1]);
    result = fibberoni(n);
    printf("%d", result);
    exit(EXIT_SUCCESS);
}