Can someone explain to me how it works? It seems like for every algorithm problem, I have to look at the answers and cant really solve it on my own.
I would not look at the solutions. What have you tried? How did you get stuck trying things?
function factorialize(num) {
let factorial;
for(let i = num - 1; i > 0; i --) {
factorial = num * i
}
return factorial;
}
factorialize(5);
what do you think is happening in this line?
do you know the definition of factorial?
I think its multiplying the number times i, and it’ll keep multyplying it until it gets to 1
What is “it”?
This line says - multiply num
by i
, ignore the contents of factorial
and overwrite the contents
so let’s consider, num
is 6
so i
starts with 5
so at first iteration we have 6 * 5
and that is saved in factorial
at next iteration we have 6 * 4
, and that is saved in factorial
, what about the previous multiplication tho?
we need to calculate 6 * 5 * 4 * 3 * 2 * 1
, is that happening?
Oh oops, no it’s not
I changed the code to this then
function factorialize(num) {
let factorial = num;
for(let i = num - 1; i > 0; i --) {
factorial *= i
}
return factorial;
}
factorialize(5);
and does that work?
No, I think I need to check if its less than 1
what is not working? when are you geting unexpected values?
Wait, I got it
function factorialize(num) {
let factorial = num;
if (num <= 1) {
return 1
}
for(let i = num - 1; i > 0; i --) {
factorial *= i
}
return factorial;
}
factorialize(5);
What is this condition for?
If the number is less than 1 (or 1), then I’ll return 1, because the factorial would be 1
There is probably a way to avoid this conditional. Can you think of one?
I’m sorry, but I have no idea
You already have a condition here. Can you use that?
Wait, I see, i>=1
?
I don’t think i > 0
and i >= 1
are any different when using integers?
But that condition stops the loop body from executing when i == 0
or i < 0
. What do you want to return when that is the case?