Thursday 19 September 2013

Javascript doesn't give correct integer output -- Project Euler 20

Javascript doesn't give correct integer output -- Project Euler 20

I'm trying to solve Project Euler Problem 20, while I think to solution is
quite trivial, turns out Javascript doesn't give me the correct output:
var fact = 1;
for (var i = 100; i > 0; i--) {
fact *= i;
}
var summed = 0;
while (fact > 0) {
summed += Math.floor(fact % 10);
fact = fact / 10;
}
console.log(summed); //587
http://jsfiddle.net/9uEFj/
Now, let's try solving 100! from the bottom (that is, 1 * 2 * 3 * ... *
100 instead of 100 * 99 * .. * 1 like before ):
var fact = 1;
for (var i = 1; i <= 100; i++) {
fact *= i;
}
var summed = 0;
while (fact > 0) {
summed += Math.floor(fact % 10);
fact = fact / 10;
}
console.log(summed); //659
http://jsfiddle.net/YX4bu/
What is happening here? Why different multiplication order give me
different result? Also, why none of the results give me the correct result
of problem 20? (648)

No comments:

Post a Comment