2017-03-01 124 views
0

代碼中的問題出現在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; 
       } 
      } 
     } 
    } 
} 
} 
+1

'k'循環裏面沒有'if'條件嗎?這根本不起作用......對於每個「i」,每個「j」只能得到k = 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; 
      } 
     } 
    } 
} 
0

使用標籤打破(或繼續)比內另一個循環:

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; 
      } 
     } 
    } 

,或者使用一個額外的方法,並返回 - 更表示,如果新的方法有一個自己的清除功能(和更好名)

public static void goldbach(int[] array) { 
    for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer 
     primeAdd(i); 
    } 
} 

private static void primeAdd(int i) { 
    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]); 
      return; 
     } 
    } 
} 

但是,作爲已經被bureaquete評論說,沒有必要爲內循環,因爲它總是被終止。