代码中的问题在于goldbach方法。我想在内部最多循环找到一对数字之后停止内部两个循环的迭代,但我不知道如何退出这两个循环。换句话说,我只想找到最外层for循环创建的每个i整数只有一对,然后继续下一个整数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;
}
}
}
}
}
}
答案 0 :(得分:0)
您可以在第二个循环中设置j的值。例如
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]);
j = i + 1; // This will end the outer loop as well.
break;
}
}
}
}
答案 1 :(得分:0)
使用标签来破坏(或继续)除内部循环之外的循环:
azure site log tail <sitename>
或使用其他方法并返回 - 如果新方法具有自己的清除功能(以及更好的名称),则表示更多
found:
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 found;
}
}
}
但是,正如bureaquete已经评论过的那样,不需要内部循环,因为它总是被终止。