I have two fib algorithm for comparison, one is mine while other is my teacher's,
1: Mine (taking 7 milsec)
function fibMineSolution(n, a = 0, b = 1, len = 1) {
if (len === n) return b;
return fib(n, b, a + b, ++len);
}
2: Teachers solution (taking 6 milsec):
function fibTeacherSolution(n: number) {
if (n < 2)
return n;
return fib(n - 1) + fib(n - 2);
}
When I tested both as follow:
const t1 = new Date().getTime();
fibMineSolution(5);
const timeTaken = new Date().getTime() - t1; // gives 7...
const t1 = new Date().getTime();
fibTeacherSolution(5);
const timeTaken = new Date().getTime() - t1; // gives 6...
As you see, sir algorithm is calling itself twice while mine is not! Also if I give larger value to mine function, It max call stack exeeds while sir algorithm doesn't has this issue,
By the way, I am new to recursion!