Reputation: 71
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
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
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)
Upvotes: 0
Views: 364
Reputation:
The product of the first 100 integers is a large number in the order of 1e158. This will be handled as a floating point number with the consequent loss of precision. See The Floating Point Guide for a fuller explanation. The results of your two multiplications match to 15 significant figures, but differ at the 16th and beyond. This is enough to throw your final result.
To do this properly you'll need to use integer arithmetic throughout - something that is well beyond Javascript's native capabilities. You'll need to handle a number of 158 digits, and write a multiplication routine yourself.
If you use a string format to store the number, the second part of your script just needs to total the digits.
Upvotes: 2