No, the method in question does not use tail recursion. Tail recursion is easily recognizable: a recursive step is the last thing that happens in a method.
After completing both recursive calls, there is one more operation in your code - adding. Thus, the method is recursive, but not recursive.
For comparison purposes, here is the recursive implementation of the fib()
method - pay attention to how we need to pass additional parameters to save the state of the recursion and, more importantly, to notice that after the operation there were no actions, the recursive call returns.
public static long fib(int n, long a, long b) { return n == 0 ? b : fib(n-1, a+b, a); }
Use it as follows:
fib(10, 1, 0)
The previous implementation will work up to n = 92, for large numbers you will have to use BigInteger
instead of long
and it is better to switch to an iterative algorithm.
source share