Test for a Prime Number in Java

// Perform a brute-force check on an integer to see if it is prime
// By definition, a number is prime if it has no factors except 1 and itself
// This method can be copied into an existing class or used as-is in the
//  class provided here.
// There are more elegant ways to detect prime numbers, but this method
//  is by far the most straight-forward.

public class Utils {
    static boolean IsPrime(long num) {
        boolean status = true;      // Hope for the best
        int i = 2;
        num = Math.abs(num);
        long limit = num / 2;
        for (i = 2; i <= limit; i++) {
            if ((num % i) == 0) {       // is num divisible by i?
                status = false;
                break;
            }
        }
        return status;
    }
}


More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working