elp1987
elp1987

Reputation: 13

Any Suggestions for Improving my Code on (Negative) Factorial (in JavaScript)?

I was doing a basic problem on coding a factorial n!:

function factorialize(num) {
  if (num < 0) {
 return undefined;
  } else if (num === 0) {
    return 1;
  }
  else {
    return num * factorialize(num - 1);
  }
}

The site I'm learning from accepted this solution, but they're only testing for nonnegative integers, i.e for n ≥ 0, not negative integers.

I got curious on how to compute a negative factorial (-n)!. Many pages say it's undefined, but I found two saying it could be defined.

The gist I got is that:

|n!| = |(-n)!|

Their absolute values are the same but the negative factorials change signs.

Examples:

4! = (-4)! = 24

5! = 120 but (-5)! = -120

The formula that I gathered from the two linked pages is:

(-n)! = |n|! * (-1)^n

And this reflects my code. From test cases, I think I've nailed it. I just want to ask if there's a better way of coding it. Someone from here remarked that using recursion is memory-inefficient.

function factorialize(num) {
 if (num === 0) {
   return 1;
  } else if (num > 0) {
     return num * factorialize(num - 1);
  } else {
     return Math.pow(-1, num) * Math.abs(num) * factorialize(Math.abs(num) - 1);  
    }
  }

// test cases below
    console.log(factorialize(-1)); // -1
    console.log(factorialize(1)); // 1
    console.log(factorialize(0)); // 1
    console.log(factorialize(-2)); // 2
    console.log(factorialize(2)); // 2
    console.log(factorialize(-3)); // -6
    console.log(factorialize(3)); // 6
    console.log(factorialize(-4)); // 24
    console.log(factorialize(4)); // 24
    console.log(factorialize(-5)); // -120
    console.log(factorialize(5)); // 120

Upvotes: 1

Views: 123

Answers (1)

Soham Kamani
Soham Kamani

Reputation: 552

You could also do this using iteration (normally everything that can be done recursively can also be done iteratively). There is also no need to raise -1 to the power of your number. It would be much more efficient, if your just checked if it was odd or even.

function factorialize(n){
  var absNum = Math.abs(n);
  var i = 1;
  var factorial = 1;
  while(i <= absNum){
    factorial *= i;
    i += 1;
  }
  if(absNum % 2 === 1 && n < 0){
    return -factorial
  }
  return factorial;
}

Upvotes: 2

Related Questions