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.