如果我們在下面列出10是3或5的倍數的所有自然數,我們得到了3,5,6和9這倍數的總和爲23Java的歐拉程序錯誤
找到的總和3或5低於1000
項目歐拉的所有倍數找到解決方案,我得到一個array out of bounds error
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);
}
}
嗯,這個例外是由於'x <= mult3.length',它應該是'x
Eran
不要那麼靜止。使用更多動態的東西 - 將數字放在'ArrayList'中。這樣你就不必知道你需要存儲的數字的數量。 –
而且 - 您可以在第一個循環中計算總和。那麼你不需要'int threeTotal = IntStream.of(mult3).sum();'line –