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

  • The Importance of Doing Laundry
    19

    We could nag, but this is better. It is less work for us to use the words of others to emphasize the importance of doing laundry. Besides, if you saw the way we dressed, you'd laugh your mouse off.

  • Data Hiding in Java
    12

    Data Hiding is an aspect of Object Oriented Programming (OOP) that allows developers to protect private data and hide implementation details. In this tutorial we examine basic data hiding techniques in Java.

  • Introduction to Windows Notepad
    5

    A useful text editor is an essential component of any personal computer. Every day we need to make notes, compose documents, and record vital pieces of information. We depend on our text editor. Microsoft provided...


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