Is prime number

This example will show how to check if a number is a prime using various straight up java techniques and apache commons.

Straight up Java

Is prime

This approach is often found in beginning java exercises where a question is asked to write a program to determine if a number is prime. A method is created with a number as parameter where the first if check is created to check if the number is divisible by 2. If it is the method returns false otherwise it proceed checking if the number can be divided by any number that is contained in the number incrementing by 2.

/**
 * Method will determine if n is prime
 *
 * @param n
 * @return boolean
 */
boolean isPrime(int n) {

    if (n % 2 == 0) {
        return false;
    } else {
        for(int i=3; i*i <=n; i+=2) {
            if(n % i == 0) {
                return false;
            }
        }
    }
    return true;
}

@Test
public void determine_if_number_is_prime_java () {

    boolean isPrimeNumber = isPrime(5779);
    assertTrue(isPrimeNumber);
}

BigInteger probable prime

@Test
public void determine_if_number_is_prime_java_big_integer () {

    Random rnd = new Random();
    BigInteger isPrimeNumber = BigInteger.probablePrime(3, rnd);

    assertEquals(5, isPrimeNumber.intValue());
}

Is prime regular expression

This regular expression will check if a number isPrime.

@Test
public void determine_if_number_is_prime_java_regular_expresison () {

    char n = 5779;
    boolean isPrimeNumber = false;
    if (!new String(new char[n]).matches(".?|(..+?)\1+")) {
        isPrimeNumber = true;
    }
    assertTrue(isPrimeNumber);
}

Apache Commons

Apache commons has a dedicated class for checking if a number is prime which contains various methods to check if a number isPrime, finding the next prime and finding the prime factors for a given number.

Is prime

@Test
public void determine_if_number_prime_with_apache_commons () {

    boolean isPrimeNumber = Primes.isPrime(5779);
    assertTrue(isPrimeNumber);
}

Next prime

@Test
public void find_next_prime_number_with_apache_commons () {

    int nextPrimeNumber = Primes.nextPrime(5780);

    assertEquals(5783, nextPrimeNumber);
}

Prime factors

@Test
public void determine_prime_factors_of_a_number_with_apache_commons () {

    List<Integer> primeFactors = Primes.primeFactors(5782);

    assertThat(primeFactors, hasItems(2, 7, 7, 59));
}