그래서 나는 언어로 연습을하기 위해 자바에서 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;
}
}
}
"유일한 것"이란 무엇을 의미합니까? 에서와 같이, 3을 초과하는'n'은'isPrime (n)'에 대해 false를 반환합니까? – discipline
'testValue % 1 == 0'은 항상 true입니다. 이것은 디버거를 사용하여 쉽게 발견 할 수있는 버그의 일종입니다. –
따로 : 관습에 따라, 당신은 보통'for' 루프에서'i'를 위해 소문자를 사용합니다. – bphilipnyc