-1

I have a recursion function which calculates factorial for a given number.

function findFactorial(num) {
  if (num < 1 || !num.isInteger) {
    return "error";
  } else {
    return num * findFactorial(num - 1);
  }
}

console.log(findFactorial(7));

I want to check if number is less then 1 OR is not integer - and return "error" for it. Code I tried above isn't working and giving me "error" every time function is called.

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
Ati
  • 304
  • 3
  • 14

2 Answers2

1

num.isInteger function is not availble in js. We have Number.isInteger(val).

Some code changes needed.

  • When a number is not an integer or is a negative number then only we need to return the error.
  • When a number reaches 1 then we need to return 1 itself to get then factorial values.

See the below code.

function findFactorial(num) {
  if (!Number.isInteger(num) || num < 0) {
    return "error";
  } else if (num <= 1) {
    return 1;
  }
  else {
    return num * findFactorial(num - 1);
  }
}

console.log(findFactorial(7));
console.log(findFactorial(-5));
console.log(findFactorial("six"));
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
1

You have three issues in your code.

  • First your code will always return "error", since you will always come to the point where num == 0.
  • Second you have no termination condition (except for the wrong return "error"), so the recursion will never return a valid value.
  • And last but not least, you try to call a function isInteger() but this function does not exist for the num object.

Here is the valid code:

function findFactorial(num) {
  if (isNaN(num) || num < 1) {
    return "error";
  }
  if (num == 1) {
    return 1;
  }
  return num * findFactorial(num - 1);
}

console.log(findFactorial(7));
Jozott
  • 2,367
  • 2
  • 14
  • 28