简体   繁体   English

Javascript没有给出正确的整数输出 - 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: 我正在尝试解决Project Euler Problem 20 ,而我认为解决方案非常简单,结果是Javascript没有给我正确的输出:

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/ http://jsfiddle.net/9uEFj/

Now, let's try solving 100! 现在,让我们尝试解决100! from the bottom (that is, 1 * 2 * 3 * ... * 100 instead of 100 * 99 * .. * 1 like before ): 从底部(即1 * 2 * 3 * ... * 100代替100 * 99 * .. * 1之前):

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/ 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? 另外,为什么没有一个结果能给出问题20的正确结果? (648) (648)

The product of the first 100 integers is a large number in the order of 1e158. 前100个整数的乘积是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. 两次乘法的结果与15位有效数字匹配,但在第16次及以后有所不同。 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. 要正确地执行此操作,您需要始终使用整数运算 - 这远远超出了Javascript的本机功能。 You'll need to handle a number of 158 digits, and write a multiplication routine yourself. 你需要处理158个数字,并自己编写一个乘法例程。

If you use a string format to store the number, the second part of your script just needs to total the digits. 如果使用字符串格式存储数字,则脚本的第二部分只需要总计数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM