Using tail recursion and Fibonacci-style recursion to solve the Fibonacci sequence

suggest change

The simplest recursive way to obtain the nth term of the Fibonacci sequence is:

int get_term_fib(int n)
{
  if (n == 0)
    return 0;
  if (n == 1)
    return 1;
  return get_term_fib(n - 1) + get_term_fib(n - 2);
}

However, this algorithm does not scale for higher terms: for bigger and bigger n, the number of function calls that you need to make grows exponentially. This can be replaced with a simple tail recursion.

int get_term_fib(int n, int prev = 0, int curr = 1)
{
  if (n == 0)
    return prev;
  if (n == 1)
    return curr;
  return get_term_fib(n - 1, curr, prev + curr);
}

Each call now calculates the next term in the Fibonacci sequence, so the number of calls grows linearly with n. A negative n never hits either base case. For a large n, prev + curr can overflow signed int, which is undefined. The two functions are alternatives; defining both makes a one-argument call ambiguous.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents