 # Am i doing it right? Algorithm challenge 2

Am i doing it right? Algorithm challenge 2
0

#1

Hey there,

I’m at the algorithm challenges and I love them!
but at the second one I feel like i cheated a little
(https://www.freecodecamp.org/challenges/factorialize-a-number)
I got everything right except for the last one, if you type 0 it should return 1, doesn’t make sense cause multiply anything with zero you’ll get zero.

so I just typed an if/else statement but I’m not sure if it’s the right way to go.

``````
function factorialize(num) {

var factorArray = [];
for(var i = 1 ; i < num ; i++){
factorArray.push(i);
}

for(var j = 1 ; j < factorArray.length ; j++){
num = num * factorArray[j];
}

if(num >= 1){
return num;
}
else{
return 1;
}

return num;
}

factorialize(0);
``````

can anyone tell me if I’m doing it right?

thnks!

#2

The factorial of 0 is a special case, and is defined to be equal to 1. And when you have to code a special case, you’d usually use an if-block for that.

You can think of factorials as the number of ways to arrange n distinct items. If you have 3 items, there are six different arrangements. If you have one item, there is only one arrangement. If there are zero items to arrange, there is one arrangement (the no-arrangement arrangement, if that makes sense).

Here’s more about zero factorial:

#3

This is much more internering than i thought. Also makes my brain melt a little bit. So I didn’t do really well then with my code. Do you have a small example on how to do it?

#4

You could compute for the factorial without using arrays and uses only one for-loop, like

``````function factorialize(num) {
// You could save a lot of computation by dealing with the special case first.
if (num === 0) {
return 1;
}

var product = 1;
for (var i = 1; i <= num; i++) {
// short for `product = product * i;`
product *= i;
}

return product;
}
``````

#5

That is a lot easier, glad I wasn’t to far off thanks man!