Possible Duplicate:
Most Elegant Way to write isPrime in java
How do I go about making this faster or better? I made it to solve a project Euler problem then optimized it, but I’m sure it’s not the best method
public static boolean prime(int number){
int limit = (int) (1 + Math.sqrt(number) );
if (number < 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for(int i= 3; i < limit; i+=2)
if(number % i == 0)
return false;
return true;
}
}
Except for its handling of the number
1, the function looks pretty good. One improvement that can be made is to make use of the fact that all primes greater than3are of the form6k ± 1.You can choose to go even further, but you’ll have to balance improved performance with increased code complexity.