It's wrong to write Fibonacci with recursive methods !!
This is an old famous example of how good / bad Algorism affects any project.
if you write Fibonatcci recursive, to calculate 120 you will need a 36-year result !!!!!!
public static int Fibonacci(int x) {
in dot net 4.0 there is a new name like BigInteger, and you can use it to improve the function
using System; using System.Collections.Generic; using System.Numerics; // link required. to this assembly
namespace Fibonaci { public class CFibonacci { public static int Fibonacci(int x) { if (x <= 1) return 1; return Fibonacci(x - 1) + Fibonacci(x - 2); } public static IEnumerable<BigInteger> BigFib(Int64 toNumber) { BigInteger previous = 0; BigInteger current = 1; for (Int64 y = 1; y <= toNumber; y++) { var auxiliar = current; current += previous; previous = auxiliar; yield return current; } } } }
and you can use it as
using System; using System.Linq; namespace Fibonaci { class Program { static void Main() { foreach (var i in CFibonacci.BigFib(10)) { Console.WriteLine("{0}", i); } var num = 12000; var fib = CFibonacci.BigFib(num).Last(); Console.WriteLine("fib({0})={1}", num, fib); Console.WriteLine("Press a key..."); Console.ReadKey(); } } }
in which case you can calculate 12000 less than a second. so
Using a recursive method is not always a good idea.
Above code imported from the blog of Wahid Nasiri, who wrote in Persian
source share