diff options
author | Vivek Patel | 2022-12-18 16:20:04 +0000 |
---|---|---|
committer | GitHub | 2022-12-18 16:20:04 +0000 |
commit | 7d6769991b0e62b4cf12766346f7a7df3bc397df (patch) | |
tree | 74f4290f81fd727bcc6c19ece77655958cd80e3e /entries/williamvietnguyen/fibberoni.c | |
parent | b69f47912fc5ddc72769d10371166088dc328b3e (diff) | |
parent | 883f7d6767492bd576f37f2b5fd4ada26e55ac83 (diff) |
Merge branch 'main' into gofib
Diffstat (limited to 'entries/williamvietnguyen/fibberoni.c')
-rw-r--r-- | entries/williamvietnguyen/fibberoni.c | 39 |
1 files changed, 39 insertions, 0 deletions
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 <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); +} |