2016-08-14 5 views
1

그래서 나는 언어로 연습을하기 위해 자바에서 codeeval을위한 mersense 스크립트를 작성하고있다 (나는 상당히 익숙하다). 한순간에 나는 수가 소수 인 경우 확인하고있어 내 방식으로 내가 정상적인 검사를하고 모든 것이 멋지다자바에서 반환 문제

public static boolean isPrime (int testValue){ 
    if (testValue < 4){ 
    return true; 
    } else if (testValue % 2 == 0){ 
    return false; 
    } else { 
    for (int I = 1; I < Math.sqrt (testValue); I++){ 
     if (testValue % I == 0){ 
     return false; 
    } 
    } 
    return true; 
    } 
} 

그러나 돌파 만 가지 일 것 같다 3. 나는 그렇게 할 수 없다 for 루프 다음에 복귀하면 뭐가 잘못 되었나요? 어떤 아이디어?

편집 :

import java.io.*; 
import java.lang.Math; 

public class Main{ 
public static void main(String[] args) throws IOException { 
    File file = new File(args[0]); 
    BufferedReader buffer = new BufferedReader(new FileReader(file)); 
    String line; 
    int n; 
    StringBuilder result = new StringBuilder(); 
    int candidate; 
    while((line = buffer.readLine()) != null){ 
     n = Integer.parseInt(line.trim()); 
     for(int i = 1; i < n; i++){ 
      candidate = mersenne(i); 
      if(isPrime(candidate)){ 
       System.out.println(candidate + " "+ isPrime(candidate)); 
       if((i+1) >= n){ 
        result.append(candidate); 
       }else{ 
        result.append(candidate + ", "); 
       } 
      } 
     } 
     System.out.println(result.toString()); 
     result = new StringBuilder(); 
    } 
} 

public static int mersenne (int testValue){ 
    return (int)Math.pow(2,testValue) - 1; 
} 
public static boolean isPrime(int testValue){ 
    if(testValue < 4 && testValue > 1){ 
     return true; 
    }else if(testValue % 2 == 0){ 
     return false; 
    }else{ 
     for(int i = 3; i <= Math.sqrt(testValue); i++){ 
      if(testValue % i == 0){ 
       return false; 
      } 
     } 
     return true; 
    } 
} 
} 
+0

"유일한 것"이란 무엇을 의미합니까? 에서와 같이, 3을 초과하는'n'은'isPrime (n)'에 대해 false를 반환합니까? – discipline

+0

'testValue % 1 == 0'은 항상 true입니다. 이것은 디버거를 사용하여 쉽게 발견 할 수있는 버그의 일종입니다. –

+0

따로 : 관습에 따라, 당신은 보통'for' 루프에서'i'를 위해 소문자를 사용합니다. – bphilipnyc

답변

6

당신은 0으로 시작 1. 모든 % 1에서 루프입니다 시작하고있는 3.

+2

.. 2 씩 증가 시키면 짝수를 확인할 필요가 없습니다. 또한 'i <= Math.sqrt (testValue)'이어야합니다. –

+0

3의 배수로 3부터 시작해야합니다. –

+0

맞습니다. 잘못된 var을보고있었습니다. <4 비트가 나를 던졌습니다. –

2

코드에서 : 여기

전체 코드입니다 다른 블록 :

:

for (int I = 1; I < Math.sqrt (testValue); I++){ 
     if (testValue % I == 0){ 
     return false; 
    } 
    } 

시작한다 I =

for (int I = 3; I < Math.sqrt (testValue); I++) 

모든 숫자 % 1은 (는) 0과 같으므로 false가 반환됩니다.

+0

그래, 그게 내게 더 높은쪽으로 지적되었다. 내가 그것을 놓친 바보 같은 느낌. – tourn171