为什么我的javascript没有返回Project Euler的第一个正确答案?

时间:2015-03-29 00:59:43

标签: javascript arrays

我正在尝试使用Javascript解决Project Euls问题第一。 我知道这不是最有说服力的解决方案,但我不明白为什么它不起作用。我取三倍,五倍于1000的倍数,然后将它们存储在两个单独的数组中。我然后将数组添加到一起,使用console.log()输出答案,我得到的答案是266333而不是正确的答案233168.有谁知道为什么?

/* Declaring Global Variables */
var n; 
var sumOfThree = 0;
var sumOfFive = 0;

/* Declaring Arrays */
multiplesOfThree = [];
multiplesOfFive = [];

/* Finding how many numbers < 1000 divide evenly by three and five then adding them to my arrays*/

console.log("Let's calculate how many numbers divide evenly by three and five in the number one thousand.");
console.log("Calculating...");

for(n = 0; n < 1000; n ++) {
    if(n % 3 === 0) { 
    multiplesOfThree.push(n);
    }
}

for(n = 0; n < 1000; n ++) {
    if(n % 5 === 0) { 
        multiplesOfFive.push(n);
    }
}

/* Letting the User know how many multiples of three exist */

console.log()
console.log("There are " + multiplesOfThree.length + " multiples of three in the number one thousand.");

/* Letting the user know how many multiples of five exist */

console.log()
console.log("There are " + multiplesOfFive.length + " multiples of five in the number one thousand.");
console.log()

/*Letting the User know the sum of the number of multiples*/

console.log("Let's get the sum of the number of multiples.");
console.log("Calculating...");
console.log(multiplesOfThree.length + multiplesOfFive.length);
console.log()

/* Letting the user know the sum of all the three multiples*/
console.log("Let's get the sum of all the three multiples")
console.log("Calculating... ");
for (i=0; i < multiplesOfThree.length; i++) {

    sumOfThree += multiplesOfThree[i];

}
console.log(sumOfThree);
console.log()

/* Letting the User know the sum of all the five multiples */

console.log("Let's get the sum of five multiples")
console.log("Calculating... ");
for (i=0; i < multiplesOfFive.length; i++) {

    sumOfFive += multiplesOfFive[i];

}
console.log(sumOfFive);
console.log()

/* Letting the user know the added sum of all the three, five multiples */

console.log("Let's add these two sums together")
console.log("Calculating... ");
var sumOfBoth = sumOfFive + sumOfThree;
console.log(sumOfBoth);

2 个答案:

答案 0 :(得分:1)

是的,因为您要添加的数字是3和5两倍的倍数。

答案 1 :(得分:0)

从1到 N 的数字之和为N*(N+1)/2

要计算您尝试计算的总和,我们需要考虑这些部分。 1到999之间可被3整除的数字之和将是从1到333,乘以3的数字之和。同样,1到999之间可被5整除的数字之和将是数字的总和从1到199,乘以5.最后,我们必须考虑到这两个总和将包括可以被 3和5整除的数字,所以我们需要减去数字的总和从1到66,乘以15。

因此,总和是:

3*(333*334)/2 + 5*(199*200)/2 - 15*(66*67)/2

从1到 N 的数字之和为N*(N+1)/2的事实我认为通常归因于高斯,尽管它不是一个非常复杂的关系,所以它可能年纪大了您可以通过考虑写出的值1到 N 来证明它是真的,并将值 N 降低到1,直接写在下面。来自两行值的每个顶部和底部对的总和显然是 N + 1 ;第一对是 N 和1,第二对是 N-1 和2,第三对是 N-2 和3,依此类推。这些对中有 N ,因此结果很明确: N N 个实例,并且由于列表加倍,我们需要除以2得到最终总和。请注意,除以2不能引入分数,因为 N N + 1 必须是偶数。