ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

Test for a Prime Number in Java

Updated on May 28, 2009
// 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;
    }
}


Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article