Basic Algorithm Scripting – Factorialize a Number

Basic Algorithm Scripting – Factorialize a Number

Problem Statement (Factorialize a Number) :

Return the factorial of the provided integer.

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 * 2 * 3 * 4 * 5 = 120

 

Solution :

function factorialize(num) {
  
  if(num == 0) {
    return 1;    
  }
  
  result = num;
  
  while(num-- > 1) {
    result = result * num;
  }
  
  return result;
}

Explanation :

The if condition in the program is to return 1 when the number passed to the function is 0, so we did it first.

Now, we need a variable to store our factorialized (Ahmm! not a valid word) result.

So, the basic logic behind is to loop multiply all the numbers from 1 to the number provided. I did it in reverse, from the number provided to 1.

I have multiplied all the numbers from the number provided as argument to the function to result variable and reduced the num variable by 1 for every loop.

And that’s how we can get our result.

You can find more problems solved in here : FreeCodeCamp – Basic Algorithm Scripting – Solved

www.000webhost.com