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


/* primality by Wilson's theorem */
wilson: procedure options( main );
   declare n binary(15)fixed;
 
   isWilsonPrime: procedure( n )returns( bit(1) );
      declare n            binary(15)fixed;
      declare ( fmodp, i ) binary(15)fixed;
      fmodp = 1;
      do i = 2 to n - 1;
         fmodp = mod( fmodp * i, n );
      end;
      return ( fmodp = n - 1 );
   end isWilsonPrime ;
 
   do n = 1 to 100;
      if isWilsonPrime( n ) then do;
         put edit( n ) ( f(3) );
      end;
   end;
end wilson ;