I made a non recursive Fibonacci function in C for fun because it can't solve 100 fast with recursion.
Did anyone else besides me do it this way
#include<stdio.h>
/*prototypes*/
double fib(int n);
int main(void)
{
int i;
for(i = 0;i <= 100;++ i)
{
printf("%1.0f \n",fib(i));
}
return 0;
}
/*non recursive fibonacci function*/
double fib(int n)
{
double prev = -1;
double result = 1;
double sum;
int i;
for(i = 0;i <= n;++ i)
{
sum = result + prev;
prev = result;
result = sum;
}
return result;
}
A few months ago, I posted this:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <math.h>
using namespace std;
//Non-recrusive: O(1)
unsigned long fib(int n)
{
return (1/sqrt(5)) * (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n));
}
//Recrusive: O(n)
unsigned long fib2(int n)
{
if(n <= 2) return 1;
else return fib2(n - 1) + fib2(n - 2);
}
//Iterative: O(n)
unsigned long fib3(int n)
{
int u = 0;
int v = 1;
int i, t;
for(i = 2; i <= n; i++)
{
t = u + v;
u = v;
v = t;
}
return v;
}
Edited by dargueta, 26 November 2010 - 02:12 PM.
Fixed code tags