From 612feb8cad7eb6a67ef69cef117e2b0ffa87b184 Mon Sep 17 00:00:00 2001 From: williamvietnguyen Date: Sat, 17 Dec 2022 05:54:35 -0500 Subject: fibberoni --- entries/williamvietnguyen/fibberoni.c | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 entries/williamvietnguyen/fibberoni.c (limited to 'entries/williamvietnguyen/fibberoni.c') diff --git a/entries/williamvietnguyen/fibberoni.c b/entries/williamvietnguyen/fibberoni.c new file mode 100644 index 0000000..e3c3c4d --- /dev/null +++ b/entries/williamvietnguyen/fibberoni.c @@ -0,0 +1,39 @@ +/* fib.c */ +#include +#include +#include + +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); +} -- cgit v1.2.3-70-g09d2