Evaluate if a given number is a prime number - Java java.lang

Java examples for java.lang:Math Number

Description

Evaluate if a given number is a prime number

Demo Code


//package com.java2s;

public class Main {
    /**//  ww  w .  j  ava 2 s . c o  m
     * Evaluate if a given number is a prime number
     * 
     * @param primeCandidate
     * @return true is primeCandidate is a prime number
     */
    public static boolean isPrime(long primeCandidate) {
        if (primeCandidate == 1) {
            return false;
        } else if (primeCandidate == 2) {
            return true;
        } else if (primeCandidate % 2 == 0) {
            return false;
        }
        long maxFactor = (long) Math.sqrt(primeCandidate);
        for (long j = 3; j <= maxFactor; j++) {
            if (primeCandidate % j == 0) {
                return false;
            }
        }
        return true;
    }
}

Related Tutorials