Reputation: 332
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!
Upvotes: 2
Views: 6386
Reputation: 536
There is two ways of doing that. First one in the loop and second one is in recursive function.
Loop version is like that:
function factorialize(num) {
for(var answer=1;num>0;num--){
answer*=num;
}
return answer;
}
And recursive one is like that.
function factorialize(num) {
if(num===0){
return 1;
}
else{
return num*factorialize(num-1);
}
}
Both of them will work with all positive integers.
Upvotes: 6
Reputation: 61
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".
Upvotes: 6
Reputation: 25
Note: This response explains which type of loop to use and hints on how to format the loop to get a factorial of 5, to get the basic format before using num
Given the example of 5! = 1 * 2 * 3 * 4 * 5 = 120, you can see there is a pattern of numbers that start at 1, end at 5, and increment by 1. You can also see that for each number between 1 and 5, you need to multiply by the next one, over and over again, in order to get the factorial.
A for loop is used to repeat a specific block of code a known number of times. In this case, you know the number of times is 5 (aka 1,2,3,4,5). The specific block of code is what you'll need to figure out based on the answer you are trying to get (which in this case is 5! = 1*2*3*4*5 = 120).
For Loop Hints: When thinking about how to write the for loop's conditions: Start the incrementing at 1, end the incrementing at 5, and increment by 1 (1,2,3,4,5)
When writing the block of code that will act upon each number, think about the relationship each number needs to have so your code essentially does this: 1*2*3*4*5
Upvotes: 0