返回java中的问题

时间:2016-08-14 01:39:50

标签: java return conditional

所以我正在为java中的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;
  }
}
然而,唯一能够通过的事情似乎是1和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;
    }
}
}

1 个答案:

答案 0 :(得分:2)

你在else块中的代码:

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

你应该从I = 3开始:

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

由于每个数字%1等于0,因此将返回false。