Monday, March 28, 2011

a reasonable implementation of prime number checking

Once again prime numbers on my mind, but this time I won't write the program in BASIC like I did 20+ years ago...

So here we go, a quick implementation in Java, and yes, I'm assuming non-negative input:
public static boolean isPrime(int n) {
    if (n==0 || n==1) return false;  // careful!
    for (int i=2; i<(n/2)+1; i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
Originally I ran the for loop all the way up to n, but half-n will suffice. There's another efficiency improvement that can be made to the algorithm, I didn't have it in my head until reading it on StackOverflow. Also there's some interesting reading material on Wolfram MathWorld.

1 comments: