Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Tail Recursion

Name: Anonymous 2011-10-19 21:09

How do i make this function tail recursive in java


public int fib(int n)
{
  return( n <= 1 ? n : fib(n-1) + fib(n-2) );
}

Name: Anonymous 2011-10-20 14:29

>>1

Like this:


public int fib(int n)
{
  int a = 1, b = 1;
  for (int i = 2; i <= n; ++i)
  {
    int t = b;
    b = a + b;
    a = t;
  }

  return t;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List