Primality by Wilson's theorem
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem..
By Wilson's thoerem, a number p is prime if p divides (p - 1)! + 1
.
Remember that 1 and all non-positive integers are not prime.
- See also
Contents
8086 Assembly[edit]
cpu 8086
org 100h
section .text
jmp demo
;;; Wilson primality test of CX.
;;; Zero flag set if CX prime. Destroys AX, BX, DX.
wilson: xor ax,ax ; AX will hold intermediate fac-mod value
inc ax
mov bx,cx ; BX = factorial loop counter
dec bx
.loop: mul bx ; DX:AX = AX*BX
div cx ; modulus goes in DX
mov ax,dx
dec bx ; Next value
jnz .loop ; If not zero yet, go again
inc ax ; fac-mod + 1 equal to input?
cmp ax,cx ; Set flags according to result
ret
;;; Demo: print primes under 256
demo: mov cx,2
.loop: call wilson ; Is it prime?
jnz .next ; If not, try next number
mov ax,cx
call print ; Otherwise, print the number
.next: inc cl ; Next number.
jnz .loop ; If <256, try next number
ret
;;; Print value in AX using DOS syscall
print: mov bp,10 ; Divisor
mov bx,numbuf ; Pointer to buffer
.digit: xor dx,dx
div bp ; Divide AX and get digit in DX
add dl,'0' ; Make ASCII
dec bx ; Store in buffer
mov [bx],dl
test ax,ax ; Done yet?
jnz .digit ; If not, get next digit
mov dx,bx ; Print buffer
mov ah,9 ; 9 = MS-DOS syscall to print a string
int 21h
ret
section .data
db '*****' ; Space to hold ASCII number for output
numbuf: db 13,10,'$'
- Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251
ALGOL W[edit]
As with the APL, Tiny BASIC (and possibly others) samples, this computes the factorials mod p at each multiplication to avoid needing numbers larger than the 32 bit limit.
begin
% find primes using Wilson's theorem: %
% p is prime if ( ( p - 1 )! + 1 ) mod p = 0 %
% returns true if n is a prime by Wilson's theorem, false otherwise %
% computes the factorial mod p at each stage, so as to %
% allow numbers whose factorial won't fit in 32 bits %
logical procedure isWilsonPrime ( integer value n ) ;
if n < 2 then false
else begin
integer factorialModN;
factorialModN := 1;
for i := 2 until n - 1 do factorialModN := ( factorialModN * i ) rem n;
factorialModN = n - 1
end isWilsonPrime ;
for i := 1 until 100 do if isWilsonPrime( i ) then writeon( i_w := 1, s_w := 0, " ", i );
end.
- Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
APL[edit]
This version avoids huge intermediate values by calculating the modulus after each step of the factorial multiplication. This is necessary for the function to work correctly with more than the first few numbers.
wilson ← {⍵<2:0 ⋄ (⍵-1)=(⍵|×)/⍳⍵-1}
- Output:
wilson {(⍺⍺¨⍵)/⍵} ⍳200 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
The naive version (using APL's built-in factorial) looks like this:
naiveWilson ← {⍵<2:0 ⋄ 0=⍵|1+!⍵-1}
But due to loss of precision with large floating-point values, it only works correctly up to number 19 even with ⎕CT set to zero:
- Output:
⎕CT←0 ⋄ naiveWilson {(⍺⍺¨⍵)/⍵} ⍳20 2 3 5 7 11 13 17 19 20
C[edit]
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
// uses wilson's theorem
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
// Can check up to 21, more will require a big integer library
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
- Output:
Is 2 prime: 1 Is 3 prime: 1 Is 4 prime: 0 Is 5 prime: 1 Is 6 prime: 0 Is 7 prime: 1 Is 8 prime: 0 Is 9 prime: 0 Is 10 prime: 0 Is 11 prime: 1 Is 12 prime: 0 Is 13 prime: 1 Is 14 prime: 0 Is 15 prime: 0 Is 16 prime: 0 Is 17 prime: 1 Is 18 prime: 0 Is 19 prime: 1 Is 20 prime: 0 Is 21 prime: 0
C#[edit]
Performance comparison to Sieve of Eratosthenes.
using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
// initialization
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
// dumps a chunk of the prime list (lst)
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
// returns the cardinal string representation of a number
static string Card(int x, string fmt = "{0:n0}") { return string.Format(fmt, x) +
"thstndrdthththththth".Substring((x % 10) << 1, 2); }
// shows the results of one type of prime tabulation
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,3} ");
WriteLine(fm2, Card(skp), Card(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
// for stand-alone computation
static BI factorial(BI n) { BI res = 1; if (n < 2) return res;
for (; n > 0; n--) res *= n; return res; }
static bool WTisPrime(BI n) { return ((factorial(n - 1) + 1) % n) == 0; }
// end stand-alone
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n++) if (!flags[n]) {
lst.Add(n); for (int k = n * n; k <= lmt; k += n) flags[k] = true; }
ShowOne(ms2, ref et2); st = DateTime.Now;
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
// stand-alone computation
WriteLine("\n" + ms1 + " stand-alone computation:");
for (BI x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
- Output:
--- Wilson's theorem method --- The first 120 primes are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 1,000th prime thru the 1,015th prime: 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081 Time taken: 164.7332ms --- Sieve of Eratosthenes method --- The first 120 primes are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 1,000th prime thru the 1,015th prime: 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081 Time taken: 4.6169ms Wilson's theorem method was 35.7 times slower than the Sieve of Eratosthenes method. Wilson's theorem method stand-alone computation: 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081 Time taken: 2727.164ms
The "slow" factor may be different on different processors and programming environments. For example, on Tio.run, the "slow" factor is anywhere between 120 and 180 times slower. Slowness most likely caused by the sluggish BigInteger library usage. The SoE method, although quicker, does consume some memory (due to the flags BitArray). The Wilson's theorem method may consume considerable memory due to the large factorials (the f variable) when computing larger primes.
The Wilson's theorem method is better suited for computing single primes, as the SoE method causes one to compute all the primes up to the desired item. In this C# implementation, a running factorial is maintained to help the Wilson's theorem method be a little more efficient. The stand-alone results show that when having to compute a BigInteger factorial for every primality test, the performance drops off considerably more.
Cowgol[edit]
include "cowgol.coh";
# Wilson primality test
sub wilson(n: uint32): (out: uint8) is
out := 0;
if n >= 2 then
var facmod: uint32 := 1;
var ct := n - 1;
while ct > 0 loop
facmod := (facmod * ct) % n;
ct := ct - 1;
end loop;
if facmod + 1 == n then
out := 1;
end if;
end if;
end sub;
# Print primes up to 100 according to Wilson
var i: uint32 := 1;
while i < 100 loop
if wilson(i) == 1 then
print_i32(i);
print_char(' ');
end if;
i := i + 1;
end loop;
print_nl();
- Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Erlang[edit]
#! /usr/bin/escript
isprime(N) when N < 2 -> false;
isprime(N) when N band 1 =:= 0 -> N =:= 2;
isprime(N) -> fac_mod(N - 1, N) =:= N - 1.
fac_mod(N, M) -> fac_mod(N, M, 1).
fac_mod(1, _, A) -> A;
fac_mod(N, M, A) -> fac_mod(N - 1, M, A*N rem M).
main(_) ->
io:format("The first few primes (via Wilson's theorem) are: ~n~p~n",
[[K || K <- lists:seq(1, 128), isprime(K)]]).
- Output:
The first few primes (via Wilson's theorem) are: [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101, 103,107,109,113,127]
F#[edit]
// Wilsons theorem. Nigel Galloway: August 11th., 2020
let wP(n,g)=(n+1I)%g=0I
let fN=Seq.unfold(fun(n,g)->Some((n,g),((n*g),(g+1I))))(1I,2I)|>Seq.filter wP
fN|>Seq.take 120|>Seq.iter(fun(_,n)->printf "%A " n);printfn "\n"
fN|>Seq.skip 999|>Seq.take 15|>Seq.iter(fun(_,n)->printf "%A " n);printfn ""
- Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069
Factor[edit]
USING: formatting grouping io kernel lists lists.lazy math
math.factorials math.functions prettyprint sequences ;
: wilson ( n -- ? ) [ 1 - factorial 1 + ] [ divisor? ] bi ;
: prime? ( n -- ? ) dup 2 < [ drop f ] [ wilson ] if ;
: primes ( -- list ) 1 lfrom [ prime? ] lfilter ;
"n prime?\n--- -----" print
{ 2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 }
[ dup prime? "%-3d %u\n" printf ] each nl
"First 120 primes via Wilson's theorem:" print
120 primes ltake list>array 20 group simple-table. nl
"1000th through 1015th primes:" print
16 primes 999 [ cdr ] times ltake list>array
[ pprint bl ] each nl
- Output:
n prime? --- ----- 2 t 3 t 9 f 15 f 29 t 37 t 47 t 57 f 67 t 77 f 87 f 97 t 237 f 409 t 659 t First 120 primes via Wilson's theorem: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 1000th through 1015th primes: 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081
Forth[edit]
: fac-mod ( n m -- r )
>r 1 swap
begin dup 0> while
dup rot * [email protected] mod swap 1-
repeat drop rdrop ;
: ?prime ( n -- f )
dup 1- tuck swap fac-mod = ;
: .primes ( n -- )
cr 2 ?do i ?prime if i . then loop ;
- Output:
128 .primes 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 ok
FreeBASIC[edit]
function wilson_prime( n as uinteger ) as boolean
dim as uinteger fct=1, i
for i = 2 to n-1
'because (a mod n)*b = (ab mod n)
'it is not necessary to calculate the entire factorial
fct = (fct * i) mod n
next i
if fct = n-1 then return true else return false
end function
for i as uinteger = 2 to 100
if wilson_prime(i) then print i,
next i
- Output:
Primes below 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Go[edit]
Needless to say, Wilson's theorem is an extremely inefficient way of testing for primalty with 'big integer' arithmetic being needed to compute factorials greater than 20.
Presumably we're not allowed to make any trial divisions here except by the number two where all even positive integers, except two itself, are obviously composite.
package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
// Only usable for n <= 20.
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
// If memo == true, stores previous sequential
// factorial calculation for odd n > 21.
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1) // computes factorial from scratch
} else {
prev.Mul(prev, r.MulRange(n-2, n-1)) // uses previous calculation
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
// sequential memoized calculation
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
- Output:
n prime --- ----- 2 true 3 true 9 false 15 false 29 true 37 true 47 true 57 false 67 true 77 false 87 false 97 true 237 false 409 true 659 true The first 120 prime numbers are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 The 1,000th to 1,015th prime numbers are: 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081
Haskell[edit]
import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
putStrLn $ see 16.take 16 $ drop 999 primes
numbers = [2,3,9,15,29,37,47,57,67,77,87,97,237,409,659]
primes = [p | p <- 2:[3,5..], isPrime p]
isPrime :: Integer -> Bool
isPrime p = if p < 2 then False else 0 == mod (succ $ product [1..pred p]) p
bagOf :: Int -> [a] -> [[a]]
bagOf _ [] = []
bagOf n xs = let (us,vs) = splitAt n xs in us : bagOf n vs
see :: Show a => Int -> [a] -> String
see n = unlines.map unwords.bagOf n.map (T.unpack.T.justifyRight 3 ' '.T.pack.show)
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep : replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss
- Output:
--- ------- p isPrime --- ------- 2 True 3 True 9 False 15 False 29 True 37 True 47 True 57 False 67 True 77 False 87 False 97 True 237 False 409 True 659 True --- ------- The first 120 prime numbers are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 The 1,000th to 1,015th prime numbers are: 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081
J[edit]
wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
Java[edit]
Wilson's theorem is an extremely inefficient way of testing for primality. As a result, optimizations such as caching factorials not performed.
import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
- Output:
Primes less than 100 testing by Wilson's Theorem 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Julia[edit]
iswilsonprime(p) = (p < 2 || (p > 2 && iseven(p))) ? false : foldr((x, y) -> (x * y) % p, 1:p - 1) == p - 1
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimesbetween(7900, 9000)[1:40])
- Output:
First 120 Wilson primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659] The first 40 Wilson primes above 7900 are: [7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269]
PARI/GP[edit]
Wilson(n) = prod(i=1,n-1,Mod(i,n))==-1
Perl[edit]
use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
my($ends_in_7, $ends_in_3);
sub is_wilson_prime {
my($n) = @_;
$n > 1 or return 0;
(factorial($n-1) % $n) == ($n-1) ? 1 : 0;
}
for (0..50) {
my $m = 3 + 10 * $_;
$ends_in_3 .= "$m " if is_wilson_prime($m);
my $n = 7 + 10 * $_;
$ends_in_7 .= "$n " if is_wilson_prime($n);
}
say $ends_in_3;
say $ends_in_7;
- Output:
3 13 23 43 53 73 83 103 113 163 173 193 223 233 263 283 293 313 353 373 383 433 443 463 503 7 17 37 47 67 97 107 127 137 157 167 197 227 257 277 307 317 337 347 367 397 457 467 487
Phix[edit]
include mpfr.e
function wilson(integer p)
mpz f = mpz_init()
mpz_fac_ui(f,p-1)
mpz_add_ui(f,f,1)
return mpz_fdiv_ui(f,p)=0
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) -- this method really is hideously slow!
- Output:
The first 25 primes: {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97} '' builtin: {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97} primes[1000..1015]: {7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081} '' builtin: {7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081} "3.4s"
Plain English[edit]
To run:
Start up.
Show some primes (via Wilson's theorem).
Wait for the escape key.
Shut down.
The maximum representable factorial is a number equal to 12. \32-bit signed
To show some primes (via Wilson's theorem):
If a counter is past the maximum representable factorial, exit.
If the counter is prime (via Wilson's theorem), write "" then the counter then " " on the console without advancing.
Repeat.
A prime is a number.
A factorial is a number.
To find a factorial of a number:
Put 1 into the factorial.
Loop.
If a counter is past the number, exit.
Multiply the factorial by the counter.
Repeat.
To decide if a number is prime (via Wilson's theorem):
If the number is less than 1, say no.
Find a factorial of the number minus 1. Bump the factorial.
If the factorial is evenly divisible by the number, say yes.
Say no.
- Output:
1 2 3 5 7 11
Python[edit]
No attempt is made to optimise this as this method is a very poor primality test.
from math import factorial
def is_wprime(n):
return n > 1 and bool(n == 2 or
(n % 2 and (factorial(n - 1) + 1) % n == 0))
if __name__ == '__main__':
c = 100
print(f"Primes under {c}:", end='\n ')
print([n for n in range(c) if is_wprime(n)])
- Output:
Primes under 100: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Raku[edit]
(formerly Perl 6)
Not a particularly recommended way to test for primality, especially for larger numbers. It works, but is slow and memory intensive.
sub postfix:<!> (Int $n) { (constant f = 1, |[\*] 1..*)[$n] }
sub is-wilson-prime (Int $p where * > 1) { (($p - 1)! + 1) %% $p }
# Pre initialize factorial routine (not thread safe)
9000!;
# Testing
put ' p prime?';
printf("%4d %s\n", $_, .&is-wilson-prime) for 2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659;
my $wilsons = (2,3,*+2…*).hyper.grep: &is-wilson-prime;
put "\nFirst 120 primes:";
put $wilsons[^120].rotor(20)».fmt('%3d').join: "\n";
put "\n1000th through 1015th primes:";
put $wilsons[999..1014];
- Output:
p prime? 2 True 3 True 9 False 15 False 29 True 37 True 47 True 57 False 67 True 77 False 87 False 97 True 237 False 409 True 659 True First 120 primes: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 1000th through 1015th primes: 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081
REXX[edit]
Some effort was made to optimize the factorial computation by using memoization and also minimize the size of the
decimal digit precision (NUMERIC DIGITS expression).
Also, a "pretty print" was used to align the displaying of a list.
/*REXX pgm tests for primality via Wilson's theorem: a # is prime if p divides (p-1)! +1*/
parse arg LO zz /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 120 /*Not specified? Then use the default.*/
if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 /*use default?*/
sw= linesize() - 1; if sw<1 then sw= 79 /*obtain the terminal's screen width. */
digs = digits() /*the current number of decimal digits.*/
#= 0 /*number of (LO) primes found so far.*/
!.= 1 /*placeholder for factorial memoization*/
$= /* " to hold a list of primes.*/
do p=1 until #=LO; oDigs= digs /*remember the number of decimal digits*/
?= isPrimeW(p) /*test primality using Wilson's theorem*/
if digs>Odigs then numeric digits digs /*use larger number for decimal digits?*/
if \? then iterate /*if not prime, then ignore this number*/
#= # + 1; $= $ p /*bump prime counter; add prime to list*/
end /*p*/
call show 'The first ' LO " prime numbers are:"
w= max( length(LO), length(word(reverse(zz),1))) /*used to align the number being tested*/
@is.0= " isn't"; @is.1= 'is' /*2 literals used for display: is/ain't*/
say
do z=1 for words(zz); oDigs= digs /*remember the number of decimal digits*/
p= word(zz, z) /*get a number for user-supplied list. */
?= isPrimeW(p) /*test primality using Wilson's theorem*/
if digs>Odigs then numeric digits digs /*use larger number for decimal digits?*/
say right(p, max(w,length(p) ) ) @is.? "prime."
end /*z*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrimeW: procedure expose !. digs; parse arg x '' -1 last; != 1; xm= x - 1
if x<2 then return 0 /*is the number too small to be prime? */
if x==2 | x==5 then return 1 /*is the number a two or a five? */
if last//2==0 | last==5 then return 0 /*is the last decimal digit even or 5? */
if !.xm\==1 then != !.xm /*has the factorial been pre-computed? */
else do; if xm>!.0 then do; base= !.0+1; _= !.0; != !._; end
else base= 2 /* [↑] use shortcut.*/
do j=!.0+1 to xm; != ! * j /*compute factorial.*/
if pos(., !)\==0 then do; parse var ! 'E' expon
numeric digits expon +99
digs = digits()
end /* [↑] has exponent,*/
end /*j*/ /*bump numeric digs.*/
if xm<999 then do; !.xm=!; !.0=xm; end /*assign factorial. */
end /*only save small #s*/
if (!+1)//x==0 then return 1 /*X is a prime.*/
return 0 /*" isn't " " */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: parse arg header,oo; say header /*display header for the first N primes*/
w= length( word($, LO) ) /*used to align prime numbers in $ list*/
do k=1 for LO; _= right( word($, k), w) /*build list for displaying the primes.*/
if length(oo _)>sw then do; say substr(oo,2); oo=; end /*a line overflowed?*/
oo= oo _ /*display a line. */
end /*k*/ /*does pretty print.*/
if oo\='' then say substr(oo, 2); return /*display residual (if any overflowed).*/
Programming note: This REXX program makes use of LINESIZE REXX program (or
BIF) which is used to determine the screen width
(or linesize) of the terminal (console). Some
REXXes don't have this BIF.
The LINESIZE.REX REXX program is included here ───► LINESIZE.REX.
- output when using the default inputs:
The first 120 prime numbers are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 2 is prime. 3 is prime. 9 isn't prime. 15 isn't prime. 29 is prime. 37 is prime. 47 is prime. 57 isn't prime. 67 is prime. 77 isn't prime. 87 isn't prime. 97 is prime. 237 isn't prime. 409 is prime. 659 is prime.
Ring[edit]
load "stdlib.ring"
decimals(0)
limit = 19
for n = 2 to limit
fact = factorial(n-1) + 1
see "Is " + n + " prime: "
if fact % n = 0
see "1" + nl
else
see "0" + nl
ok
next
Output:
Is 2 prime: 1 Is 3 prime: 1 Is 4 prime: 0 Is 5 prime: 1 Is 6 prime: 0 Is 7 prime: 1 Is 8 prime: 0 Is 9 prime: 0 Is 10 prime: 0 Is 11 prime: 1 Is 12 prime: 0 Is 13 prime: 1 Is 14 prime: 0 Is 15 prime: 0 Is 16 prime: 0 Is 17 prime: 1 Is 18 prime: 0 Is 19 prime: 1
Ruby[edit]
def w_prime?(i)
return false if i < 2
((1..i-1).inject(&:*) + 1) % i == 0
end
p (1..100).select{|n| w_prime?(n) }
- Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Sidef[edit]
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
Tiny BASIC[edit]
PRINT "Number to test"
INPUT N
IF N < 0 THEN LET N = -N
IF N = 2 THEN GOTO 30
IF N < 2 THEN GOTO 40
LET F = 1
LET J = 1
10 LET J = J + 1
REM exploits the fact that (F mod N)*J = (F*J mod N)
REM to do the factorial without overflowing
LET F = F * J
GOSUB 20
IF J < N - 1 THEN GOTO 10
IF F = N - 1 THEN PRINT "It is prime"
IF F <> N - 1 THEN PRINT "It is not prime"
END
20 REM modulo by repeated subtraction
IF F < N THEN RETURN
LET F = F - N
GOTO 20
30 REM special case N=2
PRINT "It is prime"
END
40 REM zero and one are nonprimes by definition
PRINT "It is not prime"
END
Wren[edit]
Due to a limitation in the size of integers which Wren can handle (2^53-1) and lack of big integer support, we can only reliably demonstrate primality using Wilson's theorem for numbers up to 19.
import "/math" for Int
import "/fmt" for Fmt
var wilson = Fn.new { |p|
if (p < 2) return false
return (Int.factorial(p-1) + 1) % p == 0
}
for (p in 1..19) {
Fmt.print("$2d -> $s", p, wilson.call(p) ? "prime" : "not prime")
}
- Output:
1 -> not prime 2 -> prime 3 -> prime 4 -> not prime 5 -> prime 6 -> not prime 7 -> prime 8 -> not prime 9 -> not prime 10 -> not prime 11 -> prime 12 -> not prime 13 -> prime 14 -> not prime 15 -> not prime 16 -> not prime 17 -> prime 18 -> not prime 19 -> prime
zkl[edit]
GNU Multiple Precision Arithmetic Library and primesvar [const] BI=Import("zklBigNum"); // libGMP
fcn isWilsonPrime(p){
if(p<=1 or (p%2==0 and p!=2)) return(False);
BI(p-1).factorial().add(1).mod(p) == 0
}
fcn wPrimesW{ [2..].tweak(fcn(n){ isWilsonPrime(n) and n or Void.Skip }) }
numbers:=T(2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659);
println(" n prime");
println("--- -----");
foreach n in (numbers){ println("%3d %s".fmt(n, isWilsonPrime(n))) }
println("\nFirst 120 primes via Wilson's theorem:");
wPrimesW().walk(120).pump(Void, T(Void.Read,15,False),
fcn(ns){ vm.arglist.apply("%4d".fmt).concat(" ").println() });
println("\nThe 1,000th to 1,015th prime numbers are:");
wPrimesW().drop(999).walk(15).concat(" ").println();
- Output:
n prime --- ----- 2 True 3 True 9 False 15 False 29 True 37 True 47 True 57 False 67 True 77 False 87 False 97 True 237 False 409 True 659 True First 120 primes via Wilson's theorem: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 The 1,000th to 1,015th prime numbers are: 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069