代碼中的問題出現在goldbach方法中。在最內層循環找到一對數字後,我想停止迭代內層的兩個循環,但是我不知道如何退出這兩個循環。換句話說,我只想在每個由最外面的for循環創建的整數中只找到一對,然後移動到下一個整數i。經過一次正確的迭代後停止內循環
下面是我的代碼:
import java.util.Arrays;
import java.awt.List;
import java.util.ArrayList;
// finding prime numbers using sieve of Eratosthenes and golbach's conjecture
public class Test {
public static void main(String[] args) {
int[] num = new int[1000000];
for (int i = 2; i <= num.length; i++) {
num[i - 1] = i;
}
Test.sieve(num);
Test.goldbach(num);
}
public static void sieve(int[] array) {
for (int i = 2; i < Math.sqrt(array.length); i++) {
if (array[i - 1] == 0) {
continue;
}
for (int j = 2 * i; j <= array.length; j += i) {
array[j - 1] = 0;
}
}
for (int i = 0; i < array.length; i++) {
if (array[i] != 0) {
//System.out.print(array[i] + " ");
}
}
//System.out.println(Arrays.toString(array));
}
public static void goldbach(int[] array) {
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
break;
}
}
}
}
}
}
'k'循環裏面沒有'if'條件嗎?這根本不起作用......對於每個「i」,每個「j」只能得到k = 0的值 –