DEV Community

Randy Rivera
Randy Rivera

Posted on

Factorialize a Number

  • Let's 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
  • Only integers greater than or equal to zero will be supplied to the function.

There's two ways that I know of to solve this problem:

function factorialize(num) {
let result = 1;
for (let i = 1; i <= num; i++) {
result *= i; // <--basically going to accumulate all of the numbers.
}
return result; //<-- returns 120;
}

console.log(factorialize(5)); // will display 120
Enter fullscreen mode Exit fullscreen mode
  • The for loop starts at 1 and increments each time until i is less than or equal to num which in this case is 5. When we console.log(i) we get 1, 2, 3, 4, 5.
  • I also created a variable result which is equal to 1 because if we put 0 there then every time we multiply it by 0 we get zero. the result variable is basically going to accumulate all of the numbers. We follow that by result = result times i or just result times equal i which then returns that which in this case is 120;

OR

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

// factorialize(5); // will display 120
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

  • Notice at the first line we have the terminal condition, i.e a condition to check the end of the recursion. If num == 0, then we return 1, i.e. effectively ending the recursion and informing the stack to propagate this value to the upper levels. If we do not have this condition, the recursion would go on until the stack space gets consumed, thereby resulting in a Stack Overflow

Top comments (2)

Collapse
 
jwkicklighter profile image
Jordan Kicklighter

I love these types of functional examples because they showcase real situations that benefit from tail-call optimization. Some languages (e.g. Haskell, Scheme) are optimized for this sort of recursion. That means the equivalent Haskell program would actually not cause a stack overflow. This is vital considering Haskell has no concept of an iterative loop, so recursive functions like this are sometimes the only way to express certain logical behaviors 🙂

Collapse
 
myblood profile image
Alexandr Vasilyev

Thanks, that helped me, and I'll add it to my bookmarks just in case)