+ 1

Does modulus behave differently in while loop?

I just don't understand why the answer is 36 and not 6... var x = 326; var prod = 1; while (x>0) { prod *= x%10; x = (x-x%10)/10; } console.log(prod);

11th Aug 2017, 9:19 PM
George Greene
George Greene - avatar
1 Answer
+ 9
The loop will be true until x will be greater than 0 x = 326 (326 - 326 % 10) / 10 = (326 - 6) / 10 = 320 / 10 = 32 ... then (32 - 32 % 10) / 10 = (32 - 2) / 10 = 30 / 10 = 3 ... finally (3 - 3 % 10) / 10 = (3 - 3) / 10 = 0 / 10 = loop ends! ... yeah, results are: 326 32 3 Variable prod will be equal to all of the numbers in 326 (3, 2, 6). prod = 1 prod *= 3 prod *= 2 prod *= 6 1 * 3 = 3 3 * 2 = 6 6 * 6 = 36 ... this last step is all you have to remember in similar Javascript questions like this one!
11th Aug 2017, 9:36 PM
Maz
Maz - avatar