Primality by Wilson's theorem: Difference between revisions
Add Refal
(Added solution for EDSAC.) |
Not a robot (talk | contribs) (Add Refal) |
||
(23 intermediate revisions by 13 users not shown) | |||
Line 18:
{{trans|Python}}
<
R n > 1 & (n == 2 | (n % 2 & (factorial(n - 1) + 1) % n == 0))
V c = 20
print(‘Primes under #.:’.format(c), end' "\n ")
print((0 .< c).filter(n -> is_wprime(n)))</
{{out}}
Line 32:
=={{header|8086 Assembly}}==
<
org 100h
section .text
Line 75:
section .data
db '*****' ; Space to hold ASCII number for output
numbuf: db 13,10,'$'</
{{out}}
Line 133:
241
251
</pre>
=={{header|Action!}}==
{{Trans|PL/M}}
<syntaxhighlight lang="action!">
;;; returns TRUE(1) if p is prime by Wilson's theorem, FALSE(0) otherwise
;;; computes the factorial mod p at each stage, so as to allow
;;; for numbers whose factorial won't fit in 16 bits
BYTE FUNC isWilsonPrime( CARD p )
CARD i, factorial_mod_p
BYTE result
factorial_mod_p = 1
FOR i = 2 TO p - 1 DO
factorial_mod_p = ( factorial_mod_p * i ) MOD p
OD
IF factorial_mod_p = p - 1 THEN result = 1 ELSE result = 0 FI
RETURN( result )
PROC Main()
CARD i
FOR i = 1 TO 100 DO
IF isWilsonPrime( i ) THEN
Put(' ) PrintC( i )
FI
OD
RETURN
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
=={{header|Ada}}==
<syntaxhighlight lang="ada">--
-- Determine primality using Wilon's theorem.
-- Uses the approach from Algol W
Line 176 ⟶ 210:
end Main;
</syntaxhighlight>
{{output}}
<pre>
Line 192 ⟶ 226:
{{Trans|ALGOL W}}
As with many samples on this page, applies the modulo operation at each step in calculating the factorial, to avoid needing large integeres.
<
# find primes using Wilson's theorem: #
# p is prime if ( ( p - 1 )! + 1 ) mod p = 0 #
Line 207 ⟶ 241:
FOR i TO 100 DO IF is wilson prime( i ) THEN print( ( " ", whole( i, 0 ) ) ) FI OD
END</
{{out}}
<pre>
Line 215 ⟶ 249:
=={{header|ALGOL W}}==
As with the APL, Tiny BASIC and other samples, this computes the factorials mod p at each multiplication to avoid needing numbers larger than the 32 bit limit.
<
% find primes using Wilson's theorem: %
% p is prime if ( ( p - 1 )! + 1 ) mod p = 0 %
Line 231 ⟶ 265:
for i := 1 until 100 do if isWilsonPrime( i ) then writeon( i_w := 1, s_w := 0, " ", i );
end.</
{{out}}
<pre>
Line 242 ⟶ 276:
multiplication. This is necessary for the function to work correctly with more than the first few numbers.
<
{{out}}
Line 252 ⟶ 286:
The naive version (using APL's built-in factorial) looks like this:
<
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:
Line 264 ⟶ 298:
Nominally, the AppleScript solution would be as follows, the 'mod n' at every stage of the factorial being to keep the numbers within the range the language can handle:
<
if (n < 2) then return false
set f to n - 1
Line 279 ⟶ 313:
if (isPrime(n)) then set end of output to n
end repeat
output</
{{output}}
<
In fact, though, the modding by n after every multiplication means there are only three possibilities for the final value of f: n - 1 (if n's a prime), 2 (if n's 4), or 0 (if n's any other non-prime). So the test at the end of the handler could be simplified. Another thing is that if f becomes 0 at some point in the repeat, it obviously stays that way for the remaining iterations, so quite a bit of time can be saved by testing for it and returning <tt>false</tt> immediately if it occurs. And if 2 and its multiples are caught before the repeat, any other non-prime will guarantee a jump out of the handler. Simply reaching the end will mean n's a prime.
Line 288 ⟶ 322:
It turns out too that <tt>false</tt> results only occur when multiplying numbers between √n and n - √n and that only multiplying numbers in this range still leads to the correct outcomes. And if this isn't abusing Wilson's theorem enough, multiples of 2 and 3 can be prechecked and omitted from the "factorial" process altogether, much as they can be skipped in tests for primality by trial division:
<
-- Check for numbers < 2 and 2 & 3 and their multiples.
if (n < 4) then return (n > 1)
Line 301 ⟶ 335:
return true
end isPrime</
=={{header|Arturo}}==
<
wprime?: function [n][
Line 313 ⟶ 347:
print "Primes below 20 via Wilson's theorem:"
print select 1..20 => wprime?</
{{out}}
Line 320 ⟶ 354:
2 3 5 7 11 13 17 19</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f PRIMALITY_BY_WILSONS_THEOREM.AWK
# converted from FreeBASIC
Line 343 ⟶ 377:
return(fct == n-1)
}
</syntaxhighlight>
{{out}}
<pre>
Line 356 ⟶ 390:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">100 HOME : REM 100 CLS for Chipmunk Basic
110 PRINT "Primes below 100"+CHR$(10)
120 FOR n = 2 TO 100
130 GOSUB 160
140 NEXT n
150 END
160 rem FUNCTION WilsonPrime(n)
170 fct = 1
180 FOR i = 2 TO n-1
181 a = fct * i
190 fct = a - INT(a / n) * n
200 NEXT i
210 IF fct = n-1 THEN PRINT i;" ";
220 RETURN</syntaxhighlight>
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<
fct = 1
for i = 2 to n-1
Line 370 ⟶ 423:
if wilson_prime(i) then print i; " ";
next i
end</
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">100 cls
110 print "Primes below 100"+chr$(10)
120 for i = 2 to 100
130 wilsonprime(i)
140 next i
150 end
160 function wilsonprime(n)
170 fct = 1
180 for i = 2 to n-1
190 fct = (fct*i) mod n
200 next i
210 if fct = n-1 then print i;
220 end function</syntaxhighlight>
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">for i = 2 to 100
let f = 1
for j = 2 to i - 1
let f = (f * j) % i
wait
next j
if f = i - 1 then
print i
endif
next i
end</syntaxhighlight>
{{out| Output}}<pre>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 </pre>
==={{header|GW-BASIC}}===
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|MSX_Basic}}
{{works with|QBasic}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">100 CLS : REM 100 CLS for Chipmunk Basic
110 PRINT "Primes below 100"+CHR$(10)
120 FOR N = 2 TO 100
130 GOSUB 160
140 NEXT N
150 END
160 REM FUNCTION WilsonPrime(n)
170 FCT = 1
180 FOR I = 2 TO N-1
190 FCT = (FCT*I) MOD N
200 NEXT I
210 IF FCT = N-1 THEN PRINT I;" ";
220 RETURN</syntaxhighlight>
==={{header|Minimal BASIC}}===
{{works with|QBasic}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">110 PRINT "Primes below 100"
120 FOR n = 2 TO 100
130 GOSUB 160
140 NEXT n
150 GOTO 250
160 rem FUNCTION WilsonPrime(n)
170 LET f = 1
180 FOR i = 2 TO n-1
181 LET a = f * i
190 LET f = a - INT(a / n) * n
200 NEXT i
210 IF f = n-1 THEN 230
220 RETURN
230 PRINT i
240 RETURN
250 END</syntaxhighlight>
==={{header|MSX Basic}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
==={{header|QBasic}}===
Line 377 ⟶ 513:
{{works with|Run BASIC}}
{{trans|FreeBASIC}}
<
fct = 1
FOR i = 2 TO n - 1
Line 388 ⟶ 524:
FOR i = 2 TO 100
IF wilsonprime(i) THEN PRINT i; " ";
NEXT i</
==={{header|Quite BASIC}}===
{{works with|QBasic}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">100 CLS
110 PRINT "Primes below 100": PRINT
120 FOR n = 2 TO 100
130 GOSUB 160
140 NEXT n
150 GOTO 250
160 rem FUNCTION WilsonPrime(n)
170 LET f = 1
180 FOR i = 2 TO n-1
181 LET a = f * i
190 LET f = a - INT(a / n) * n
200 NEXT i
210 IF f = n-1 THEN 230
220 RETURN
230 PRINT i;" ";
240 RETURN
250 END</syntaxhighlight>
==={{header|PureBasic}}===
{{trans|FreeBASIC}}
<
fct.i = 1
For i.i = 2 To n-1
Line 413 ⟶ 570:
PrintN("")
Input()
CloseConsole()</
==={{header|Run BASIC}}===
{{works with|QBasic}}
{{trans|FreeBASIC}}
<
for i = 2 to 100
if wilsonprime(i) = 1 then print i; " ";
Line 430 ⟶ 587:
next i
if fct = n-1 then wilsonprime = 1 else wilsonprime = 0
end function</
==={{header|True BASIC}}===
<
LET fct = 1
FOR i = 2 TO n - 1
Line 445 ⟶ 602:
IF wilsonprime(i) = 1 THEN PRINT i; " ";
NEXT i
END</
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<
for i = 2 to 100
if wilson_prime(i) print i, " ";
Line 462 ⟶ 619:
next i
if fct = n-1 then return True else return False : fi
end sub</
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
let wilson(n) = valof
$( let f = n - 1
if n < 2 then resultis false
for i = n-2 to 2 by -1 do
f := f*i rem n
resultis (f+1) rem n = 0
$)
let start() be
for i = 1 to 100 if wilson(i) do
writef("%N*N", i)</syntaxhighlight>
{{out}}
<pre>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</pre>
=={{header|C}}==
<
#include <stdint.h>
#include <stdio.h>
Line 504 ⟶ 701:
return 0;
}</
{{out}}
<pre>Is 2 prime: 1
Line 530 ⟶ 727:
{{libheader|System.Numerics}}
Performance comparison to Sieve of Eratosthenes.
<
using System.Linq;
using System.Collections;
Line 597 ⟶ 794:
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}</
{{out|Output @ Tio.run}}
<pre style="white-space: pre-wrap;">--- Wilson's theorem method ---
Line 638 ⟶ 835:
=={{header|C++}}==
<
#include <iostream>
Line 672 ⟶ 869:
}
}
}</
{{out}}
Line 707 ⟶ 904:
=={{header|CLU}}==
<
wilson = proc (n: int) returns (bool)
if n<2 then return (false) end
Line 726 ⟶ 923:
end
stream$putl(po, "")
end start_up </
{{out}}
<pre>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</pre>
Line 732 ⟶ 929:
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
(defun factorial (n)
(if (< n 2) 1 (* n (factorial (1- n)))) )
Line 741 ⟶ 938:
(unless (zerop n)
(zerop (mod (1+ (factorial (1- n))) n)) ))
</syntaxhighlight>
{{out}}
Line 759 ⟶ 956:
=={{header|Cowgol}}==
<
# Wilson primality test
Line 786 ⟶ 983:
i := i + 1;
end loop;
print_nl();</
{{out}}
Line 794 ⟶ 991:
=={{header|D}}==
{{trans|Java}}
<
import std.stdio;
Line 820 ⟶ 1,017:
}
writeln;
}</
{{out}}
<pre>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</pre>
=={{header|Dart}}==
{{trans|Swift}}
<syntaxhighlight lang="Dart">
BigInt factorial(BigInt n) {
if (n == BigInt.zero) {
return BigInt.one;
}
BigInt result = BigInt.one;
for (BigInt i = n; i > BigInt.zero; i = i - BigInt.one) {
result *= i;
}
return result;
}
bool isWilsonPrime(BigInt n) {
if (n < BigInt.from(2)) {
return false;
}
return (factorial(n - BigInt.one) + BigInt.one) % n == BigInt.zero;
}
void main() {
var wilsonPrimes = [];
for (var i = BigInt.one; i <= BigInt.from(100); i += BigInt.one) {
if (isWilsonPrime(i)) {
wilsonPrimes.add(i);
}
}
print(wilsonPrimes);
}
</syntaxhighlight>
{{out}}
<pre>
[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]
</pre>
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc wilson(word n) bool:
word f, i;
if n<2 then
false
else
f := n - 1;
for i from n-2 downto 2 do
f := (f*i) % n
od;
(f+1) % n = 0
fi
corp
proc main() void:
word i;
for i from 1 upto 100 do
if wilson(i) then
write(i, ' ')
fi
od
corp</syntaxhighlight>
{{out}}
<pre>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</pre>
=={{header|EasyLang}}==
{{trans|BASIC256}}
<syntaxhighlight>
func wilson_prime n .
fct = 1
for i = 2 to n - 1
fct = fct * i mod n
.
return if fct = n - 1
.
for i = 2 to 100
if wilson_prime i = 1
write i & " "
.
.
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
=={{header|EDSAC order code}}==
{{trans|Pascal}}
A translation of the Pascal short-cut algorithm, for 17-bit) EDSAC signed integers. Finding primes in the range 65436..65536 took 80 EDSAC minutes, so there is not much point in implementing the unshortened algorithm or extending to 35-bit integers.
<
[Primes by Wilson's Theoem, for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
Line 962 ⟶ 1,248:
PF [acc = 0 on entry]
[end]
</syntaxhighlight>
{{out}}
<pre>
Line 970 ⟶ 1,256:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
#! /usr/bin/escript
Line 984 ⟶ 1,270:
io:format("The first few primes (via Wilson's theorem) are: ~n~p~n",
[[K || K <- lists:seq(1, 128), isprime(K)]]).
</syntaxhighlight>
{{Out}}
<pre>
Line 993 ⟶ 1,279:
=={{header|F_Sharp|F#}}==
<
// 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 ""</
{{out}}
<pre>
Line 1,008 ⟶ 1,294:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-08-14}}
<
math.factorials math.functions prettyprint sequences ;
Line 1,024 ⟶ 1,310:
"1000th through 1015th primes:" print
16 primes 999 [ cdr ] times ltake list>array
[ pprint bl ] each nl</
{{out}}
<pre>
Line 1,058 ⟶ 1,344:
=={{header|Fermat}}==
<
=={{header|Forth}}==
<syntaxhighlight lang="forth">
: fac-mod ( n m -- r )
>r 1 swap
Line 1,073 ⟶ 1,359:
: .primes ( n -- )
cr 2 ?do i ?prime if i . then loop ;
</syntaxhighlight>
{{Out}}
<pre>
Line 1,081 ⟶ 1,367:
=={{header|FreeBASIC}}==
<
dim as uinteger fct=1, i
for i = 2 to n-1
Line 1,093 ⟶ 1,379:
for i as uinteger = 2 to 100
if wilson_prime(i) then print i,
next i</
{{out}}
Primes below 100
Line 1,101 ⟶ 1,387:
53 59 61 67 71
73 79 83 89 97</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn WilsonPrime( n as long ) as BOOL
long i, fct = 1
BOOL result
for i = 2 to n -1
fct = (fct * i) mod n
next i
if fct == n - 1 then exit fn = YES else exit fn = NO
end fn = result
long i
print "Primes below 100:"
for i = 2 to 100
if fn WilsonPrime(i) then print i
next
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
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
</pre>
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Primality_by_Wilson%27s_theorem}}
'''Solution'''
[[File:Fōrmulæ - Primality by Wilson's theorem 01.png]]
'''Test cases'''
[[File:Fōrmulæ - Primality by Wilson's theorem 02.png]]
[[File:Fōrmulæ - Primality by Wilson's theorem 03.png]]
=={{Header|GAP}}==
<
# p is prime if ( ( p - 1 )! + 1 ) mod p = 0
Line 1,123 ⟶ 1,467:
prime := [];
for i in [ -4 .. 100 ] do if isWilsonPrime( i ) then Add( prime, i ); fi; od;
Display( prime );</
{{out}}
Line 1,135 ⟶ 1,479:
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.
<
import (
Line 1,209 ⟶ 1,553:
}
fmt.Println()
}</
{{out}}
Line 1,244 ⟶ 1,588:
=={{header|Haskell}}==
<
import Data.List
Line 1,278 ⟶ 1,622:
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</
{{out}}
<pre>
Line 1,314 ⟶ 1,658:
=={{header|J}}==
<syntaxhighlight lang="j">
wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
</syntaxhighlight>
=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
fn factorial_modulo<T>(anon n: T, modulus: T, accumulator: T = 1) throws -> T => match n {
(..0) => { throw Error::from_string_literal("Negative factorial") }
0 => accumulator
else => factorial_modulo(n - 1, modulus, accumulator: (accumulator * n) % modulus)
}
fn is_prime(anon p: i64) throws -> bool => match p {
(..1) => false
else => factorial_modulo(p - 1, modulus: p) + 1 == p
}
fn main() {
println("Primes under 100: ")
for i in (-100)..100 {
if is_prime(i) {
print("{} ", i)
}
}
println()
}
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
=={{header|Java}}==
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;
Line 1,353 ⟶ 1,726:
}
</syntaxhighlight>
{{out}}
Line 1,368 ⟶ 1,741:
''''Adapted from Julia and Nim''''
<
def facmod($n; $m):
reduce range(2; $n+1) as $k (1; (. * $k) % $m);
Line 1,379 ⟶ 1,752:
# Notice that `infinite` can be used as the second argument of `range`:
"First 10 primes after 7900:",
[limit(10; range(7900; infinite) | select(isPrime))]</
{{out}}
<syntaxhighlight lang="sh">
Prime numbers between 2 and 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]
First 10 primes after 7900:
[7901,7907,7919,7927,7933,7937,7949,7951,7963,7993]</
=={{header|Julia}}==
<
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
Line 1,394 ⟶ 1,767:
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimesbetween(7900, 9000)[1:40])
</
<pre>
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]
Line 1,402 ⟶ 1,775:
=={{header|Lua}}==
<
function isWilsonPrime( n )
Line 1,417 ⟶ 1,790:
io.write( " " .. n )
end
end</
{{out}}
<pre>
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
</pre>
=={{header|MAD}}==
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(N)
ENTRY TO WILSON.
WHENEVER N.L.2, FUNCTION RETURN 0B
F = 1
THROUGH FM, FOR I = N-1, -1, I.L.2
F = F*I
FM F = F-F/N*N
FUNCTION RETURN N.E.F+1
END OF FUNCTION
PRINT COMMENT $ PRIMES UP TO 100$
THROUGH TEST, FOR V=1, 1, V.G.100
TEST WHENEVER WILSON.(V), PRINT FORMAT NUMF, V
VECTOR VALUES NUMF = $I3*$
END OF PROGRAM</syntaxhighlight>
{{out}}
<pre>PRIMES UP TO 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</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
WilsonPrimeQ[1] = False;
WilsonPrimeQ[p_Integer] := Divisible[(p - 1)! + 1, p]
Select[Range[100], WilsonPrimeQ]</
{{out}}
Prime factors up to a 100:
<pre>{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}</pre>
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (show (filter wilson [1..100]) ++ "\n")]
wilson :: num->bool
wilson n = False, if n<2
= test (n-1) (n-2), otherwise
where test f i = f+1 = n, if i<2
= test (f*i mod n) (i-1), otherwise</syntaxhighlight>
{{out}}
<pre>[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]</pre>
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE WilsonPrimes;
FROM InOut IMPORT WriteCard, WriteLn;
VAR i: CARDINAL;
PROCEDURE Wilson(n: CARDINAL): BOOLEAN;
VAR
f, i: CARDINAL;
BEGIN
IF n<2 THEN RETURN FALSE END;
f := 1;
FOR i := n-1 TO 2 BY -1 DO
f := f*i MOD n
END;
RETURN f + 1 = n
END Wilson;
BEGIN
FOR i := 1 TO 100 DO
IF Wilson(i) THEN
WriteCard(i, 3)
END
END;
WriteLn
END WilsonPrimes.</syntaxhighlight>
{{out}}
<pre> 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</pre>
=={{header|Nim}}==
<
proc facmod(n, m: int): int =
Line 1,448 ⟶ 1,909:
echo "Prime numbers between 2 and 100:"
echo primes.join(" ")</
{{out}}
Line 1,455 ⟶ 1,916:
=={{header|PARI/GP}}==
<
</syntaxhighlight>
=={{header|Pascal}}==
Line 1,464 ⟶ 1,925:
(2) Short cut, based on an observation in the AppleScript solution: if during the calculation of (n - 1)! a partial product is divisible by n, then n is not prime. In fact it suffices for a partial product and n to have a common factor greater than 1. Further, such a common factor must be present in s!, where s = floor(sqrt(n)). Having got s! modulo n we find its HCF with n by Euclid's algorithm; then n is prime if and only if the HCF is 1.
<
program PrimesByWilson;
uses SysUtils;
Line 1,538 ⟶ 1,999:
ShowPrimes( @WilsonShortCut, 4294967195, 4294967295 {= 2^32 - 1});
end.
</syntaxhighlight>
{{out}}
<pre>
Line 1,558 ⟶ 2,019:
=={{header|Perl}}==
{{libheader|ntheory}}
<
use warnings;
use feature 'say';
Line 1,579 ⟶ 2,040:
say $ends_in_3;
say $ends_in_7;</
{{out}}
<pre>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
Line 1,586 ⟶ 2,047:
=={{header|Phix}}==
Uses the modulus method to avoid needing gmp, which was in fact about 7 times slower (when calculating the full factorials).
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">wilson</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">facmod</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
Line 1,609 ⟶ 2,070:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" '' builtin: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">get_primes</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">1015</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">..</span><span style="color: #000000;">1015</span><span style="color: #0000FF;">]})</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 1,620 ⟶ 2,081:
=={{header|Plain English}}==
<
Start up.
Show some primes (via Wilson's theorem).
Line 1,648 ⟶ 2,109:
Find a factorial of the number minus 1. Bump the factorial.
If the factorial is evenly divisible by the number, say yes.
Say no.</
{{out}}
<pre>
Line 1,655 ⟶ 2,116:
=={{header|PL/I}}==
<
wilson: procedure options( main );
declare n binary(15)fixed;
Line 1,674 ⟶ 2,135:
end;
end;
end wilson ;</
{{out}}
<pre>
Line 1,684 ⟶ 2,145:
=={{header|PL/M}}==
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
<
/* P IS PRIME IF ( ( P - 1 )! + 1 ) MOD P = 0 */
Line 1,732 ⟶ 2,193:
END;
EOF</
{{out}}
<pre>
Line 1,747 ⟶ 2,208:
The PL/I include file "pg.inc" can be found on the [[Polyglot:PL/I and PL/M]] page.
Note the use of text in column 81 onwards to hide the PL/I specifics from the PL/M compiler.
<
wilson_100H: procedure options (main);
Line 1,798 ⟶ 2,259:
END;
EOF: end wilson_100H ;</
{{out}}
<pre>
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
</pre>
=={{header|PROMAL}}==
<syntaxhighlight lang="promal">
;;; Find primes using Wilson's theorem:
;;; p is prime if ( ( p - 1 )! + 1 ) mod p = 0
;;; returns TRUE(1) if p is prime by Wilson's theorem, FALSE(0) otherwise
;;; computes the factorial mod p at each stage, so as to allow
;;; for numbers whose factorial won't fit in 16 bits
PROGRAM wilson
INCLUDE library
FUNC BYTE isWilsonPrime
ARG WORD p
WORD i
WORD fModP
BYTE result
BEGIN
fModP = 1
IF p > 2
FOR i = 2 TO p - 1
fModP = ( fModP * i ) % p
IF fModP = p - 1
result = 1
ELSE
result = 0
RETURN result
END
WORD i
BEGIN
FOR i = 1 TO 100
IF isWilsonPrime( i )
OUTPUT " #W", i
END
</syntaxhighlight>
{{out}}
<pre>
Line 1,806 ⟶ 2,307:
=={{header|Python}}==
No attempt is made to optimise this as this method is a [https://en.wikipedia.org/wiki/Wilson%27s_theorem#Primality_tests very poor primality test].
<
def is_wprime(n):
Line 1,818 ⟶ 2,319:
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])</
{{out}}
Line 1,826 ⟶ 2,327:
=={{header|Quackery}}==
<
[ dup 2 < iff
Line 1,836 ⟶ 2,337:
500 times
[ i^ prime if
[ i^ echo sp ] ]</
{{out}}
Line 1,847 ⟶ 2,348:
Not a particularly recommended way to test for primality, especially for larger numbers. It ''works'', but is slow and memory intensive.
<syntaxhighlight lang="raku"
sub is-wilson-prime (Int $p where * > 1) { (($p - 1)! + 1) %% $p }
Line 1,864 ⟶ 2,365:
put "\n1000th through 1015th primes:";
put $wilsons[999..1014];</
{{out}}
<pre> p prime?
Line 1,899 ⟶ 2,400:
Also, a "pretty print" was used to align the displaying of a list.
<
parse arg LO zz /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 120 /*Not specified? Then use the default.*/
Line 1,951 ⟶ 2,452:
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
Line 1,986 ⟶ 2,487:
</pre>
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout <Filter Wilson <Iota 100>>>;
};
Wilson {
s.N, <Compare s.N 2>: '-' = F;
s.N = <Wilson s.N 1 <- s.N 1>>;
s.N s.A 1, <- s.N 1>: { s.A = T; s.X = F; };
s.N s.A s.C = <Wilson s.N <Mod <* s.A s.C> s.N> <- s.C 1>>;
};
Iota {
s.N = <Iota 1 s.N>;
s.N s.N = s.N;
s.N s.M = s.N <Iota <+ 1 s.N> s.M>;
};
Filter {
s.F = ;
s.F t.I e.X, <Mu s.F t.I>: {
T = t.I <Filter s.F e.X>;
F = <Filter s.F e.X>;
};
};</syntaxhighlight>
{{out}}
<pre>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</pre>
=={{header|Ring}}==
<
load "stdlib.ring"
Line 2,002 ⟶ 2,530:
ok
next
</syntaxhighlight>
Output:
<pre>
Line 2,026 ⟶ 2,554:
Alternative version computing the factorials modulo n so as to avoid overflow.
<
limit = 100
Line 2,042 ⟶ 2,570:
fmodp %= n
next i
return fmodp = n - 1</
{{out}}
Line 2,048 ⟶ 2,576:
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
</pre>
=={{header|RPL}}==
{{works with|HP|48S}}
≪ '''IF''' DUP 1 > '''THEN'''
DUP → p j
≪ 1
'''WHILE''' 'j' DECR 1 > '''REPEAT''' j * p MOD '''END'''
1 + p MOD NOT
≫
'''ELSE''' DROP 0 '''END'''
≫ '<span style="color:blue">WILSON?<span>' STO
=={{header|Ruby}}==
<
return false if i < 2
((1..i-1).inject(&:*) + 1) % i == 0
Line 2,056 ⟶ 2,595:
p (1..100).select{|n| w_prime?(n) }
</syntaxhighlight>
{{out}}
<pre>[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]
Line 2,062 ⟶ 2,601:
=={{header|Rust}}==
<
let mut f = 1;
while n != 0 && f != 0 {
Line 2,102 ⟶ 2,641:
p += 1;
}
}</
{{out}}
Line 2,135 ⟶ 2,674:
7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081
</pre>
=={{header|Scala}}==
{{trans|Java}}
<syntaxhighlight lang="Scala">
import scala.math.BigInt
object PrimalityByWilsonsTheorem extends App {
println("Primes less than 100 testing by Wilson's Theorem")
(0 to 100).foreach(i => if (isPrime(i)) print(s"$i "))
private def isPrime(p: Long): Boolean = {
if (p <= 1) return false
(fact(p - 1).+(BigInt(1))).mod(BigInt(p)) == BigInt(0)
}
private def fact(n: Long): BigInt = {
(2 to n.toInt).foldLeft(BigInt(1))((fact, i) => fact * BigInt(i))
}
}
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
=={{header|SETL}}==
<syntaxhighlight lang="setl">program wilsons_theorem;
print({n : n in {1..100} | wilson n});
op wilson(p);
return p>1 and */{1..p-1} mod p = p-1;
end op;
end program;</syntaxhighlight>
{{out}}
<pre>{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}</pre>
=={{header|Sidef}}==
<
n > 1 || return false
(n-1)! % n == n-1
Line 2,151 ⟶ 2,727:
say is_wilson_prime_fast(2**43 - 1) #=> false
say is_wilson_prime_fast(2**61 - 1) #=> true</
=={{header|Swift}}==
Line 2,157 ⟶ 2,733:
Using a BigInt library.
<
func factorial<T: BinaryInteger>(_ n: T) -> T {
Line 2,176 ⟶ 2,752:
}
print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))</
{{out}}
Line 2,183 ⟶ 2,759:
=={{header|Tiny BASIC}}==
<
INPUT N
IF N < 0 THEN LET N = -N
Line 2,208 ⟶ 2,784:
40 REM zero and one are nonprimes by definition
PRINT "It is not prime"
END</
=={{header|Wren}}==
{{libheader|Wren-
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./gmp" for Mpz
var t = Mpz.new()
var wilson = Fn.new { |p|
if (p < 2) return false
return (
}
var primes = [2]
var i = 3
while (primes.count < 1015) {
if (wilson.call(i)) primes.add(i)
i = i + 2
}
var candidates = [2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659]
System.print(" n | prime?\n------------")
for (cand in candidates) Fmt.print("$3d | $s", cand, wilson.call(cand))
System.print("\nThe first 120 prime numbers by Wilson's theorem are:")
Fmt.tprint("$3d", primes[0..119], 20)
System.print("\nThe 1,000th to 1,015th prime numbers are:")
System.print(primes[-16..-1].join(" "))</syntaxhighlight>
{{out}}
<pre>
------------
2 | true
3 | true
9 | false
15 | false
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 by 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 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
</pre>
=={{header|XPL0}}==
{{trans|ALGOL W}}
<syntaxhighlight lang "XPL0"> \ 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
function IsWilsonPrime; integer N ;
integer FactorialModN, I;
begin
FactorialModN := 1;
for I := 2 to N - 1 do FactorialModN := rem( FactorialModN * I / N );
return FactorialModN = N - 1
end \isWilsonPrime\ ;
integer I;
for I := 1 to 100 do if IsWilsonPrime( I ) then [IntOut(0, I); ChOut(0, ^ )]</syntaxhighlight>
{{out}}
<pre>
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 </pre>
=={{header|zkl}}==
{{libheader|GMP}} GNU Multiple Precision Arithmetic Library and primes
<
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 }) }</
<
println(" n prime");
println("--- -----");
Line 2,267 ⟶ 2,888:
println("\nThe 1,000th to 1,015th prime numbers are:");
wPrimesW().drop(999).walk(15).concat(" ").println();</
{{out}}
<pre>
|