2017-06-01 39 views
-2

我一直在修補這個代碼幾個小時,我只是無法讓它輸出正確的答案。誰能告訴我我要去哪裏?此版本正在輸出104033項目euler 7 - 我完全卡住了,無法弄清楚

package Euler; 

public class prime100001 { 

    private static boolean isPrime(long num) { 
     if (num == 2 || num == 3){ 
      return true; 
     } 
     if (num % 2 == 0){ 
      return false; 
     } 
     for (int i = 3; i * i < num; i += 2){ 
      if (num % i == 0){ 
       return false; 
      } 
     } 
     return true; 
    } 

    public static void main (String [] args){ 

     int counter = 0; 
     int primenum = 1; 

     while(counter < 10001){ 
      primenum += 2; 
      if(isPrime(primenum)){ 
       counter ++; 
      } 
     } 
     System.out.println(primenum); 
    } 

} 
+0

您正在跳過「2」,這是第一個素數。另外一個快速搜索給出了這個:https://stackoverflow.com/questions/19143200/calculating-the-10001st-prime-number也許從那裏的提示可以幫助你,以及:) – mimre

+0

我已經看到該職位之前問我的問題但它並沒有幫我弄清楚我的問題。我正在尋找特定的解釋,說明爲什麼我的代碼沒有達到我的預期。在我發佈問題之前,我重寫了大約6次 – Pedro

回答

0

只是想確認一下,您是否打印10,001st素數?

public class prime100001 { 
    private static boolean isPrime(long num) { 
     if (num == 2 || num == 3){ 
      return true; 
     } 
     if (num % 2 == 0){ 
      return false; 
     } 
     for (int i = 3; (i * i) <= num; i += 1){ 
      // Changed the condition from < to <=, as you need to capture squares 
      // (e.g. when num = 9, original method will return false as i * i = 9 < 9 is false. 
      // Also changed the increment from 2 to 1. 
      if (num % i == 0){ 
       return false; 
      } 
     } 
     return true; 
    } 

    public static void main(String [] args){ 

     int counter = 0; 

     int lastPrime = 1; 
     while(counter < 10001){ 
      lastPrime += 1; 
      // Changed increment to include 2 in the count, plus 
      // not skipping any other ints to test. 
      if (isPrime(lastPrime)){ 
       counter++; 
      } 
     } 
     System.out.println(lastPrime); 
     // Shows 104,743 
     // 10,000th prime: https://primes.utm.edu/lists/small/10000.txt 
    } 
} 

希望這會有所幫助。 ;)

+0

爲什麼在for循環中將增量更改爲1?你不需要檢查偶數的素數。除此之外,很好的編輯。謝謝您的幫助 – Pedro