tourn171
tourn171

Reputation: 36

return issues in java

So I'm writing a mersense script for codeeval in java to get some practice with the language (I'm fairly new to it). At one point I'm checking if the number is prime and in my method I do the normal checks and everything looks great

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;
  }
}

however the only things getting through seem to be 1 and 3. Can I not do that return after the for loop is that what's wrong? Any ideas?

Edit:

Here is the full code:

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;
    }
}
}

Upvotes: 1

Views: 108

Answers (2)

yellowB
yellowB

Reputation: 3020

your code in the else block:

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

you should start with I=3:

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

Since every number % 1 equals to 0 so false will be returned.

Upvotes: 2

Mark Olsson
Mark Olsson

Reputation: 320

You're starting the loop at 1. Everything % 1 is 0. Start at 3.

Upvotes: 6

Related Questions