Java欧拉程序错误

标签 java

如果我们列出所有 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/

相关文章:

java - 检查Java中的一组特定元字符\$或\,

java - java中的对象身份哈希码

java - 我可以在已打开的 JTDS 连接上更改 'appName' 吗?

java - 如何在使用不同 Java 版本的 POM 中拥有额外的编译目标?

java - 从获取文本字段字符串逐行写入或打印到文本文件

java - 带有 Retrofit 2 的多个转换器

java - Android:将 BasicNameValuePairs 的 ArrayList 传递给另一个 Activity

java - while 循环 Java 的意外输出

java - 相等的对象必须具有相等的哈希码?

java - RecyclerView 以编程方式单击