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


function wilson(integer n)
    integer facmod = 1
    for i=2 to n-1 do
        facmod = remainder(facmod*i,n)
    end for
    return facmod+1=n
end function
 
atom t0 = time()
sequence primes = {}
integer p = 2 
while length(primes)<1015 do
    if wilson(p) then
        primes &= p
    end if
    p += 1
end while
printf(1,"The first 25 primes: %V\n",{primes[1..25]})
printf(1,"          builtin: %V\n",{get_primes(-25)})
printf(1,"primes[1000..1015]: %V\n",{primes[1000..1015]})
printf(1,"         builtin: %V\n",{get_primes(-1015)[1000..1015]})
?elapsed(time()-t0)
