2

I'm looking for an implementation in Apex to determine if a number is prime or not.

Motivation: I was using testing primality as an example of the edge cases and challenges in Test driven development and realized there isn't a good reference implantation available in Apex.

3

I came up with the following. It is more or less an exact translation of the C# example from StackOverflow by Soner Gönül.

Note that it includes a boundary for the square root of the number being checked as there is no need to check higher factors.

Larger primes are going to be a challenge as divisibility by all odd numbers from 3 upward will be checked up to the boundary.

public static boolean isPrimeNumber(integer toTest) {
    if (toTest == null) throw new IllegalArgumentException('null');
    if (toTest <= 1) return false;
    if (toTest == 2) return true;
    if (Math.mod(toTest, 2) == 0) return false;

    integer boundary = (integer)Math.Floor(Math.Sqrt(toTest));
          
    for (integer i = 3; i <= boundary; i += 2) {
        if (Math.mod(toTest, i) == 0) {
            return false;
        }
    }
    
    return true; 
}

Very basic test case for the first 25 primes. Filling in the remainder is left as an exercise to the reader.

@IsTest
public static void longerCheck() {
    integer[] knownPrimes = new List<integer>{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
        
    for(integer i = -1; i <= 100; i++) {
        boolean isIPrime = MathImplementation.isPrimeNumber(i);
        boolean shouldBePrime = knownPrimes.contains(i);
        System.assertEquals(shouldBePrime, isIPrime, 'Failed on ' + i);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.