Factorialize a Number (A Question of Math)

Factorialize a Number (A Question of Math)
0.0 0

#1

function psychoMath(num) {
var x = 1;
for(var y = num; y > 0; y–) {
x *= y;
}
return x;
}

psychoMath(5);

First off, I get the code works. Great. But I fail to see the math. I cannot wrap my mind around it.

Sure, the code forces the called number to multiply itself against decrements of itself, but when I look at the loop, it suggests that 5 is turned into 4 in the first run, meaning 4 * 1, not 5 * 4…

Unless I’m mistaken, the product is stored, replacing the value of X and is multiplied by the next decrement. So, the loop basically runs as “Stored Value * Decrement of Original Number” until terminated.

X * = Y, or basically, X = X * (Y - 1 each run):
First Run, 1 * 4= 4;
Second Run, 4 * 3= 12;
Third Run, 12 * 2=24;
Fourth Run, 24*1 = 24;
Basic, ya?

Well, 5 * 24= 120. That’s what the solution calls for… but, I don’t see where that fits the loop UNLESS:
Fifth Run, somehow (Y = 1 ;1 > 0; Y–) triggers a Y = 5 instead of 0 where X is still stored as 24, thus 5 * 24= 120…

OR, am I looking at the code completely wrong in terms of it’s mathematical execution?

I know if it went 5 * 4=20, 20 * 3=60, 60 * 2=120, 120 * 1=120 it’d make more sense, so is the original value of (num) multiplied by the value of variable x first? If so, could someone break down how the code executes that process before it begins initiating the loop cycle? Does the decrement not begin until after the first loop?

I might be overlooking something incredibly simple -such is my Achilles Heel- but, if anyone is willing to answer, by-all-means, please do. I crave a deeper understanding than simply knowing the code works… I want to know How & Why it works the way it does.

Thanks in advance.


#2

You could print both X and Y inside the loop to see whats going on. Also, I think you got it, as you mentioned somewhere in your post: Y is decremented AFTER the code inside the loop is executed.
So on the 1st run X=1 and Y=5:
X = 15
2nd run (X=5 and Y=4):
X = 5
4
and so on you get 120*1 on the last run;

Anyways, when you get a problem like that you can always print the values in the middle of your process to see whats going on.


#3

It doesn’t suggest that at all. The increment/decrement operator of a for loop only executes at the beginning of each subsequent loop, not before the initial execution is performed. so 5 * 1 is 5, then 5 becomes 4, then 3, then 2 and so on.