Primality by Wilson's theorem

func is_wilson_prime_slow(n) {
    n > 1 || return false
    (n-1)! % n == n-1
}

func is_wilson_prime_fast(n) {
    n > 1 || return false
    factorialmod(n-1, n) == n-1
}

say 25.by(is_wilson_prime_slow)     #=> [2, 3, 5, ..., 83, 89, 97]
say 25.by(is_wilson_prime_fast)     #=> [2, 3, 5, ..., 83, 89, 97]

say is_wilson_prime_fast(2**43 - 1)   #=> false
say is_wilson_prime_fast(2**61 - 1)   #=> true

Last updated