I'm currently taking a course on Free Code Camp and it's asking me return a factorial for any given number. However, I'm kind of stuck on the question (please forgive me, math isn't my strong point, haha). Here's what it asks:
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 = 120f
And here's the starting code:
function factorialize(num) {
return num;
}
factorialize(5);
I'm not looking for a direct answer to the question, but I just really want to know how to start. Thanks for any help in advance!
function factorialize(num) {
var myNum = 1;
for (i=1; i<=num;i++){
myNum = myNum * i;
}
return myNum;
}
factorialize(5);
First I created a var to hold our answer (myNum).
Then I created a loop that started at 1 and up to (and including) the value of the number we are factorializing... As the loop runs, we multiply myNum to the value of i, saving the new value as myNum, so it will be multiplied by the next number in the loop...
Once the loop has finished, we return our answer using the "return myNum".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With