Thursday, 4 November 2010

Finding if a number is a prime

public class Math {
public static boolean isPrime(final long number) {
if (number == 2)
return true;
if (number < 2)
return false;
if(number % 2 == 0)
return false;
long maxCheck = (long) Math.sqrt(number);
for (long i = 3; i <= maxCheck; i += 2) {
if (number % i == 0)
return false;
}
return true;
}
}
view raw Math.java hosted with ❤ by GitHub
Update 06/04/2012
Modified the for loop as proposed by Alan (comment #1) which makes the method roughly twice as fast.