Skip to content

Instantly share code, notes, and snippets.

@gnp
Created July 14, 2010 03:00
Show Gist options
  • Save gnp/474954 to your computer and use it in GitHub Desktop.
Save gnp/474954 to your computer and use it in GitHub Desktop.
Unconventional tiny solution to fib(n) Fibonacci sequence programming problem c. 2005-04-19
#include <math.h>
#include <stdio.h>
unsigned int fibalt(unsigned int n) { return pow(1.618033988749, n) / 2.2360679774 + 0.5; }
/*unsigned int fibalt(unsigned int n) { return pow(1.618033988749, n) / sqrt(5) + 0.5; }*/
unsigned int fib(unsigned int n) {
unsigned int a[2] = { 0, 1 };
unsigned int i = 0;
for (; n > 0; --n) {
i = !i;
a[i] = a[0] + a[1];
}
return a[i];
}
void test(unsigned int n, unsigned int f) {
unsigned int g = fib(n);
if (g == f) {
printf("[OK] %2u == fib(%u)\n", f, n);
}
else {
printf("[NOT OK] %2u != fib(%u) (== %u)\n", f, n, g);
}
}
int main(int argc, char * argv[])
{
printf("sizeof(unsigned int) == %lu\n\n", sizeof(unsigned int));
unsigned int i;
for (i = 0; i < 48; i++) {
unsigned int f = fib(i);
unsigned int g = fibalt(i);
if (f == g) {
printf("fib(%3u) = %12u == %12u)\n", i, f, g);
}
else {
printf("fib(%3u) = %12u != %12u)\n", i, f, g);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment