Tuesday, November 30, 2010

Project Ideas Numbers - Fibonacci Sequence

Tackling the Fibonacci project was far easier but still yielded new knowledge.

Recursion is horrible on performance compared to iterative or tail-recursion (assuming the compiler supports tail optimization).


public static class FibonacciSequence
  {
    public static long CalculateRecurse(int term)
    {
      if (term<1)
        throw new ArgumentOutOfRangeException("term""must be >0");
      const byte f0 = 0;
      const byte f1 = 1;
      if (term<2)
        return term;
      return CalculateRecurse(term-1)+CalculateRecurse(term-2);
    }
    public static long CalculateWhile(int term)
    {
      int i = 1, k = 0;
      while (i<=term)
      {
        k+=i;
        ++i;
      }
      return k;
    }
 
    public static long CalculateTail(int term)
    {
      if (term<1)
        throw new ArgumentOutOfRangeException("term""must be >0");
      return CalculateTail(term, 1, 1);
    }
 
    private static long CalculateTail(int term, int iter, int acc)
    {
      if (iter==term)
        return acc;
      return CalculateTail(term, ++iter, acc+iter);
    }
  }

No comments:

Post a Comment