Search code examples
javascriptfactorial

Factorial multiplied by the number itself


Apart from doing the factorial recursively,how could we solve using the for loop?

function factorial(num){
for(var i=num;i>0;i--){
num*=i
}
return num;
}
factorial(3);
//18

answer should be 6 but prints 18

when I run this code say for any number x,the factorial result is again multiplied by x. factorial(3) gives 6*3... factorial(5) gives 120*5.What could be the problem?.Thanks


Solution

  • You have already the value of num as result and you multiply it again with this value. You could start the iteration with the next smaller value and iterate as you already do.

    function factorial(num) {
        for (var i = num - 1; i > 0; i--) {
            num *= i;
        }
        return num;
    }
    console.log(factorial(3));

    With a while loop, and a shorter comparison with a prefix decrement.

    function factorial(num) {
        var i = num;
        while (--i) {
            num *= i;
        }
        return num;
    }
    console.log(factorial(3));