Factorial Functions

I went to CoderByte to see what kind of challenges are out there to stay fresh with. There was one about calculating factorials. It goes like this:

Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24. For the test cases, the range will be between 1 and 18 and the input will always be an integer. 

This one was pretty easy. I just set up a loop and ran through the numbers.

function FirstFactorial(num) { 
var f = 1;
for (var i = 1; i <= num; i++) {
f = i * f;
}
return f;
}

After I was done, I saw that the code hint was to use a recursive function. Admittedly, that would be better looking code. It looks something like this:

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

Both functions get the job done.

Leave a Reply

Your email address will not be published. Required fields are marked *