为什么不是't我的javascript向Project Euler返回正确答案's排名第一

Why isn't my javascript returning the correct answer to Project Euler's Number One?

本文关键字:答案 Project 我的 javascript Euler 为什么不 返回      更新时间:2023-09-26

我正在尝试使用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);

是的,因为您要将3和5的倍数相加两次。

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

要计算你要计算的总和,我们需要考虑各个部分。可被3整除的从1到999的数字的和将是从1到333的数字的总和,乘以3。类似地,可被5整除的从1到999的数字的和将是从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+1N实例,由于列表加倍,我们需要除以2才能得到最终和。请注意,除以2不能引入分数,因为NN+1必须是偶数。