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


import BigInt
 
func factorial<T: BinaryInteger>(_ n: T) -> T {
  guard n != 0 else {
    return 1
  }
 
  return stride(from: n, to: 0, by: -1).reduce(1, *)
}
 
 
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
  guard n >= 2 else {
    return false
  }
 
  return (factorial(n - 1) + 1) % n == 0
}
 
print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))