Is this the most efficient way to find if a number is prime? I can't think of a better way and it seems to run pretty
public boolean primes(int num){
for(int i = 2; i < num; i++){
if(num % i == 0){
System.out.println(num + " is not prime");
return false;
}
}
System.out.println(num + " is prime");
return true;
}
Answers
Loginand verify email to answer
A faster method would be to skip all even numbers and only try up to the square root of the number.
public static boolean isPrime(int num){
if ( num > 2 && num%2 == 0 ) {
System.out.println(num + " is not prime");
return false;
}
int top = (int)Math.sqrt(num) + 1;
for(int i = 3; i < top; i+=2){
if(num % i == 0){
System.out.println(num + " is not prime");
return false;
}
}
System.out.println(num + " is prime");
return true;
}