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; }
Last edited by HAL 9000; 06-23-2008 at 01:32 AM.
Hi HAL 9000!
Your code looks good. I have not tried your code but it seems to be working. I want to ask a question (just for sharing fun along with you) as to how long your code can extent i.e until what number.
I tend to do factorials, permutations, and combinations in loops for the same reason.
Hi WingedPanther!
Would you like to share the fun with us by giving the program for factorials, permutations, and combinations?
My favorite place: http://gallery.techarena.in/showphoto.php/photo/9260
A few months ago, I posted this:
Code:#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; }
Last edited by dargueta; 11-26-2010 at 02:12 PM. Reason: Fixed code tags
Hi WingedPanther!
Your code is awesome. I think you have a great mind.
Good going.![]()
My favorite place: http://gallery.techarena.in/showphoto.php/photo/9260
It's a side-effect of being a mathematician: math algorithms come REALLY easily to me.
Hi WingedPanther!
I think you love mathematics. Have you tried some thing like derivatives or integrations, sine, cosine, etc.
My favorite place: http://gallery.techarena.in/showphoto.php/photo/9260
I've got a master's in math... yes, I love math![]()
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks