-1

function factorial(num) {
  var factorialValue = 1;
  if (num === 0) {
    return factorialValue;
  } else {
    for (var i = num; i <= 1; i--) {
      factorialValue *= i;
    }
    return factorialValue;
  }
}

console.log(factorial(10));
console.log(factorial(5));
console.log(factorial(3));
console.log(factorial(0));

What's the problem in my code? It works only 1.

// thx for your codes!!!

vrintle
  • 5,501
  • 2
  • 16
  • 46
ipsae
  • 1
  • 1

2 Answers2

1

function factorial(num) {
  var factorialValue = 1;
  for (var i = num; i > 1; i--) {
    factorialValue *= i;
  }
  return factorialValue;
}

console.log(factorial(10));
console.log(factorial(5));
console.log(factorial(3));
console.log(factorial(0));

But I think you can use memoization (or recursion) instead of for-loops.

function factorial (n){
  if (n==0 || n==1)
    return 1;
  return factorial(n-1)*n;
} 

console.log(factorial(10));
vrintle
  • 5,501
  • 2
  • 16
  • 46
Kid
  • 1,160
  • 2
  • 14
  • 31
  • You can also remove the __if__ condition, as `0<1` evaluates to false before the very first iter. However, it'll make it ~1% cryptic. – vrintle Apr 09 '20 at 12:17
0

You can use a more simple code, using recursion. Enjoy!

function factorial(num) {
  if (num === 0) {
    return 1;
  } else {
    return num * factorial(num-1);
  }
}

console.log(factorial(10));
console.log(factorial(5));
console.log(factorial(3));
console.log(factorial(0));