如果我们列出所有 10 以下且是 3 或 5 的倍数的自然数,我们会得到 3、5、6 和 9。这些倍数的总和是 23。
求 1000 以下的所有 3 或 5 的倍数之和。
项目欧拉找到了解决方案,我收到数组越界错误
import java.awt.List;
import java.util.Vector;
import java.util.ArrayList;
import java.util.stream.*;
//print the sum of the multiples of 3 and 5 below 1000
public class multiples_of_3_and_5 {
public static void main(String[] args) {
int mult3[] = new int[200];
int mult5[] = new int[200];
for (int i = 1; i <= 1000; i+=3 -1) {
for (int x = 0; x <= mult3.length; x++) {
mult3[x] = i;
}
}
for (int i = 1; i <= 1000; i+=5 -1 ) {
for(int x = 0; x <= mult5.length; x++) {
mult5[x] = i;
}
}
int threeTotal = IntStream.of(mult3).sum();
int fiveTotal = IntStream.of(mult5).sum();
System.out.println(threeTotal);
System.out.println(fiveTotal);
}
}
最佳答案
您可以在没有任何循环的情况下解决这个问题。只需计算相关 arithmetic progressions 的总和即可.
等差数列的和为 n(a1+an)/2,其中 a1 是第一个元素,an 是最后一个元素,n 是元素的数量。
3
1 到 999 之间的倍数之和为 (3+999)*333/2
1到999之间5
的倍数之和为(5+995)*199/2
这两个和都包含15
的倍数,所以你必须减去1到999之间15
的倍数之和,即(15+990)*66/2
因此所需的总金额为
(3+999)*333/2 + (5+995)*199/2 - (15+990)*66/2
关于Java欧拉程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46387672/