2017-08-06 50 views
2

遺憾的「修復我的代碼」後檢查一個int是首要的Java

編輯:更多有關的for環比質數,現在也解決了語法。

我的任務是從控制檯取出一個int並打印出(在不同的行上)從1到n的所有素數。 我的方法從n開始,檢查它的素數,然後將n遞減1並循環,直到n = 2。 要檢查一個數是否爲素數,我運行一個循環,檢查是潛水的剩餘部分,x的數量等於零,x從2開始並在根(n)處停止。 現在,這一切都在理論上,並閱讀我的代碼,我沒有看到它出錯的地方。

public class Prime { 
public static boolean isPrime(int n) { 
    boolean result = true; 
    for (int x = 2; x>=sqrt(n); x++) { 
     if ((n % x) == 0) { 
      result = false; 
      break; 
     } else { 
      x++; 
     } 
    } 
    return result; 
} 

public static void main(String[] args) { 
    Scanner intIn = new Scanner(System.in); 
    int i = intIn.nextInt(); 
    while (i>=2) { 
     if (isPrime(i)) { 
      System.out.println(i); 
      i--; 
     } else { 
      i--; 
     } 
    } 
    } 
} 

例如爲10的輸入將返回10(連同9,8,7,6,5,3),即使isPrime()檢查是否10%2 == 0,然後設置到result假。 我在這裏錯過了什麼?

我再次爲煩人(輕微重複)的問題表示歉意。

+0

的可能的複製[如何在Java中工作這種素數測試?](https://stackoverflow.com/questions/19514680/how-does-this-prime-number-test-in-java-工作) – Ice

回答

3

for循環的條件是條件繼續循環,而不是條件停止它。您需要<=更換>=

for (int x = 2; x<=sqrt(n); x++) { 
    // Here -----^ 
+0

我通過切換到while循環並像以前一樣手動增加x來解決我的問題。這些方法純粹是風格還是偏好? – 420fedoras

2

您遞增x兩次,循環的條件應該是x<=sqrt(n)

for (int x = 2; x>=sqrt(n); x++) { // here 
    if ((n % x) == 0) { 
     result = false; 
     break; 
    } else { 
     x++; // and here 
    } 
} 

正確的邏輯應該是:

public static boolean isPrime(int n) { 
    for (int x = 2; x<=sqrt(n); x++) { 
     if ((n % x) == 0) { 
      return false; 
     } 
    } 
    return true; 
} 
+0

我的印象是if語句必須有其他語句? – 420fedoras

+1

@ 420fedoras不,不是必需的。 – Eran

1

在循環x必須小於或等於 因此,將(int x = 2; x> = sqrt(n); x ++)的表達式更改爲 for(int x = 2; x < = sqrt(n); x ++)

1

試試吧,它更清晰簡潔。

public static boolean isPrime(int candidate) { 
     int candidateRoot = (int) Math.sqrt((double) candidate); 
     return IntStream.rangeClosed(2, candidateRoot) 
       .noneMatch(i -> candidate % i == 0); // return true if the candidate 
                // isn't divisible for any of the 
                // numbers in the stream 
    } 

    public static void main(String[] args) { 
     Scanner intIn = new Scanner(System.in); 
     int i = intIn.nextInt(); 

     List<Integer> primeList = IntStream.rangeClosed(2, i) 
       .filter(candidate -> isPrime(candidate)) 
       .boxed() 
       .collect(toList()); 
     System.out.println(primeList); 

     // Another way 
     Map<Boolean, List<Integer>> primeAndNotPrimeMap = IntStream.rangeClosed(2, i) 
       .boxed() 
       .collect(partitioningBy(candidate -> isPrime(candidate))); 
     System.out.println(primeAndNotPrimeMap); 


    }