Jmainol
Jmainol

Reputation: 437

unexpected result on recursive function

I followed the path of the whole execution and according my calculations it should be return 24, but in fact it returns 7

function factorial(x) {
    if (x < 0) return;
    if (x === 0) return 1;
    return x + 1 * factorial(x - 1);
  }

let x = factorial(3);

console.log(x); //7

I´m likely not understand properly the recursive functions

Upvotes: 0

Views: 55

Answers (1)

John Krakov
John Krakov

Reputation: 375

You seem to understand the basics of recursive programming quite well, however I'm not sure you fully understand how the factorial function works.

For example:

3! = 3*2*1 = 6

4! = 4*3*2*1 = 24

You could express this in a recursive way :

a(0) = 1

a(n) = a(n - 1) * n

Implementing this logic in your code you would get the following :

function factorial(x) {
  if (x < 0) return;
  if (x === 0) return 1;
  return x * factorial(x - 1);
}

console.log(factorial(4))

Which returns 24 as expected.

Upvotes: 3

Related Questions