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.
Actually "< sqrt(n)+1" will suffice.
ReplyDelete