Search code examples
javascriptfor-loopfactorial

Why doesn't this give me the factorial?


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

  console.log(FirstFactorial(8))

I just want to know what writing my code like this doesn't print the factorial? Instead I only get 56, which is 8 * 7. I thought that if i use the for loop that it would keep going?


Solution

  • Using:

    for(var i = num - 1; i > 0; i--) {
        return num * i; 
    }
    

    It will return num*(num-1) value. Since it will return the value in the first iteration.

    Instead use:

    Using recursion:

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

    or:

    fact=num;
    for(var i = num - 1; i > 0; i--) {
        fact*=i; 
    }
    return fact;
    

    EDIT: On demand of OP to explain how the return would work in the recursion method.

    Regarding Recursion:

    return num*FirstFactorial(num-1)
    

    actually first multiplies num with the return value of FirstFactorial(num-1) which would be (n-1)!. Hence what actually will happen is:

    1. FirstFactorial(num-1) is called. (FirstFactorial function is called with parameter num-1.
    2. The return value of FirstFactorial(num-1) which is (num-1)! is multiplied with the value of num to get num!.
    3. This value (num!) is then returned by the function FirstFactorial() when passed with parameter num or FirstFactorial(num)

    Now on calling FirstFactorial(num-1) inside the FirstFactorial(num), FirstFactorial function will again be executed checking the first if condition. If it fails, it will return the value of (n-1)*FirstFactorial(num-1 - 1). This will recurse until first if condition is satisfied and value is returned without calling the FirstFactorial again.

    You can also think the function as:

    function FirstFactorial(num) {
        if(num==1)
            return num;
        else {
            a = FirstFactorial(num-1);
            a = a * num;
            return a;
        }
    }