[英]Why isn't my javascript returning the correct answer to Project Euler's Number One?
我正在尝试使用Javascript解决Euls问题1。 我知道这不是最有效的解决方案,但是我不明白为什么它不起作用。 我将三,五的倍数放在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);
是的,因为您要将3和5的倍数相加两次。
从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 + 1 ,并且由于列表被加倍,我们需要除以2以获得最终总和。 请注意,除以2不能引入分数,因为N或N + 1必须是偶数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.