-1

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!

asdsad
  • 91
  • 1
  • 5
  • Possible duplicate of [How can I benchmark JavaScript code?](https://stackoverflow.com/questions/1003855/how-can-i-benchmark-javascript-code) – Paul Sep 16 '19 at 10:45

1 Answers1

0

You can see the difference for larger n, for example, n = 100. The first algorithm time complexity is Theta(n), but the second one is Theta(2^n). Hence, for n = 100, the first algorithm needs 100 recursion and comparison, but the second one needs near 2^100!

Anyhow, for the small value of n you can see the difference, by running 30 times (for example) and compare the average running time.

OmG
  • 15,398
  • 7
  • 42
  • 71
  • sir which solution is faster ? mine or sir? mine math is so much weak! – asdsad Sep 16 '19 at 10:24
  • @asdsad As I've explained, yours is faster. – OmG Sep 16 '19 at 10:27
  • But sir, when I tested my solution as follow: ` const t1 = new Date().getTime(); fib(5); console.log(new Date().getTime() - t1) ` , it gave 7 milliseconds with my solution while 6 with sir's solution, – asdsad Sep 16 '19 at 10:35
  • @asdsad I don't know if you read my answer or not, please test it for greater `n` to see the difference. For example, for `n = 50`. – OmG Sep 16 '19 at 10:40