View Single Post
  #5 (permalink)  
Old 06-24-2008, 07:50 AM
John's Avatar   
John John is offline
Co-Administrator
 
Join Date: Jul 2006
Age: 20
Posts: 3,569
Last Blog:
Tidy up your HTML
Credits: 0
Rep Power: 20
John has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond repute
Send a message via AIM to John Send a message via MSN to John
Default Re: Fibonacci with no recursion for fun

Quote:
Originally Posted by HAL 9000 View Post
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
Code:
#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:

C++ Code:
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <iostream>
  4. #include <math.h>
  5. using namespace std;
  6.  
  7. //Non-recrusive: O(1)
  8. unsigned long fib(int n)
  9. {
  10.      return (1/sqrt(5)) * (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n));
  11. }
  12.  
  13. //Recrusive: O(n)
  14. unsigned long fib2(int n)
  15. {
  16.     if(n <= 2) return 1;
  17.     else return fib2(n - 1) + fib2(n - 2);
  18. }
  19.  
  20. //Iterative: O(n)
  21. unsigned long fib3(int n)
  22. {
  23.     int u = 0;
  24.     int v = 1;
  25.     int i, t;
  26.  
  27.     for(i = 2; i <= n; i++)
  28.     {
  29.         t = u + v;
  30.         u = v;
  31.         v = t;
  32.     }
  33.     return v;       
  34. }
Reply With Quote

Sponsored Links