-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.

2
  • What is isInteger? Commented Apr 16, 2021 at 13:30
  • 2
    Almost got it by accident, it's Number.isInteger. Commented Apr 16, 2021 at 13:34

2 Answers 2

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));

Sign up to request clarification or add additional context in comments.

Comments

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"));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.