Task

Write a boolean function that tells whether a given integer is prime using Wilson's theorem.

By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.

Remember that 1 and all non-positive integers are not prime.



See also

 Cut-the-knot: Wilson's theorem.
 Wikipedia: Wilson's theorem


# find primes using Wilson's theorem:
#    p is prime if ( ( p - 1 )! + 1 ) mod p = 0
 
isWilsonPrime := function( p )
    local fModP, i;
    fModP := 1;
    for i in [ 2 .. p - 1 ] do fModP := fModP * i; fModP := fModP mod p; od;
    return fModP = p - 1;
end; # isWilsonPrime
 
prime := [];
for i in [ -4 .. 100 ] do if isWilsonPrime( i ) then Add( prime, i ); fi; od;
Display( prime );