Skip to content

Instantly share code, notes, and snippets.

@barrucadu
Created October 26, 2011 14:29
Show Gist options
  • Save barrucadu/1316523 to your computer and use it in GitHub Desktop.
Save barrucadu/1316523 to your computer and use it in GitHub Desktop.
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/* ***** Caching stuff ***** */
double *fibcache = NULL;
int fibcache_size = 0;
bool
fibcache_hit (int n)
{
return (fibcache_size > n);
}
double
fibcache_get (int n)
{
return fibcache[n];
}
void
fibcache_add (int n, double f)
{
if (fibcache_hit (n)) return;
if (fibcache_size <= n)
{
fibcache = realloc (fibcache, (size_t)(n + 1) * sizeof (double));
fibcache_size = n;
}
fibcache[n] = f;
}
/* ***** Fib function ***** */
double
fib (int n)
{
double f;
if (fibcache_hit (n))
f = fibcache_get (n);
else
f = (n < 2) ? n : fib (n - 1) + fib (n - 2);
fibcache_add (n, f);
return f;
}
/* ***** Test ***** */
int
main (void)
{
for (int i = 0; i < 50; i++)
printf ("fib(%i) = %.0f\n", i, fib (i));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment