# Factorialize a Number - Iterative vs Recursive

Tell us what’s happening:
I have 2 questions.

1. I tried both the iterative and recursive ways of solving this. Between the two, the iterative way seems to be quicker to respond. So is there any benefit to the recursive way?
2. In both cases, when I enter a large enough number, the function seems to return Infinity when I console.log the return value. How could I print the actual result?

``````
function factorialize(num) {
// if(num===0){
//   return 1;
// }else{
//   let factorial = 1;
//   for(let i=1;i<=num;i++){
//     factorial *= i;
//     console.log(i + ":" + factorial);
//   }
//   return factorial;
// }
if(num===0){
return 1;
}else{
return num*factorialize(num-1);
}

}

console.log(factorialize(1000));
``````

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36`.

1. Recursion just looks cooler 2. JavaScript’s `Number` type can’t represent numbers larger than 2^53. One solution is to create a string or use `BigInt` object:

``````function factorialize(num) {
num = BigInt(num);
if (num === 0n) {
return 1;
}
let factorial = 1n;
for (let i = 1; i <= num; i++) {
factorial *= BigInt(i);
}

return factorial.toString();
}

console.log(factorialize(1000));
``````

This won’t work on fcc, because it lacks support of `BigInt`, but you can copy/paste it in your browser console if you’re using Chrome.

1 Like