Primality by trial division: Difference between revisions

m (→‎Functional: Fix link and comment: Perl 6 --> Raku)
 
(109 intermediate revisions by 45 users not shown)
Line 9:
Use trial division.
 
Even numbers overgreater twothan   '''2'''   may be eliminated right away.
 
A loop from   '''3'''   to   '''√{{overline| n }}  ''' will suffice,   but other loops are allowed.
Line 25:
*   [[sequence of primes by Trial Division]]
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">F is_prime(n)
I n < 2
R 0B
L(i) 2..Int(sqrt(n))
I n % i == 0
R 0B
R 1B</syntaxhighlight>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Primality by trial division 26/03/2017
PRIMEDIV CSECT
USING PRIMEDIV,R13 base register
Line 89 ⟶ 98:
XDEC DS CL12 temp for xdeco
YREGS
END PRIMEDIV</langsyntaxhighlight>
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
=={{header|68000 Assembly}}==
<syntaxhighlight lang="68000devpac">isPrime:
; REG USAGE:
; D0 = input (unsigned 32-bit integer)
; D1 = temp storage for D0
; D2 = candidates for possible factors
; D3 = temp storage for quotient/remainder
; D4 = total count of proper divisors.
 
MOVEM.L D1-D4,-(SP) ;push data regs except D0
MOVE.L #0,D1
MOVEM.L D1,D2-D4 ;clear regs D1 thru D4
 
CMP.L #0,D0
BEQ notPrime
CMP.L #1,D0
BEQ notPrime
CMP.L #2,D0
BEQ wasPrime
 
MOVE.L D0,D1 ;D1 will be used for temp storage.
AND.L #1,D1 ;is D1 even?
BEQ notPrime ;if so, it's not prime!
 
MOVE.L D0,D1 ;restore D1
 
MOVE.L #3,D2 ;start with 3
 
computeFactors:
DIVU D2,D1 ;remainder is in top 2 bytes, quotient in bottom 2.
MOVE.L D1,D3 ;temporarily store into D3 to check the remainder
SWAP D3 ;swap the high and low words of D3. Now bottom 2 bytes contain remainder.
CMP.W #0,D3 ;is the bottom word equal to 0?
BNE D2_Wasnt_A_Divisor ;if not, D2 was not a factor of D1.
 
ADDQ.L #1,D4 ;increment the count of proper divisors.
CMP.L #2,D4 ;is D4 two or greater?
BCC notPrime ;if so, it's not prime! (Ends early. We'll need to check again if we made it to the end.)
 
D2_Wasnt_A_Divisor:
MOVE.L D0,D1 ;restore D1.
ADDQ.L #1,D2 ;increment D2
 
 
CMP.L D2,D1 ;is D2 now greater than D1?
BLS computeFactors ;if not, loop again
 
CMP.L #1,D4 ;was there only one factor?
BEQ wasPrime ;if so, D0 was prime.
 
notPrime:
MOVE.L #0,D0 ;return false
MOVEM.L (SP)+,D1-D4 ;pop D1-D4
RTS
 
wasPrime:
MOVE.L #1,D0 ;return true
MOVEM.L (SP)+,D1-D4 ;pop D1-D4
RTS
;end of program</syntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program testPrime64.s */
Line 193 ⟶ 262:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">class ZMLA_ROSETTA definition
public
create public .
Line 298 ⟶ 367:
RETURN.
endmethod.
ENDCLASS.</langsyntaxhighlight>
 
=={{header|ABC}}==
<syntaxhighlight lang="ABC">HOW TO REPORT prime n:
REPORT n>=2 AND NO d IN {2..floor root n} HAS n mod d = 0
 
FOR n IN {1..100}:
IF prime n: WRITE 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</pre>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun is-prime-r (x i)
(declare (xargs :measure (nfix (- x i))))
(if (zp (- (- x i) 1))
Line 310 ⟶ 388:
(defun is-prime (x)
(or (= x 2)
(is-prime-r x 2)))</langsyntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC IsPrime(CARD a)
CARD i
 
IF a<=1 THEN
RETURN (0)
FI
FOR i=2 TO a/2
DO
IF a MOD i=0 THEN
RETURN (0)
FI
OD
RETURN (1)
 
PROC Test(CARD a)
IF IsPrime(a) THEN
PrintF("%I is prime%E",a)
ELSE
PrintF("%I is not prime%E",a)
FI
RETURN
 
PROC Main()
Test(13)
Test(997)
Test(1)
Test(6)
Test(120)
Test(0)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Primality_by_trial_division.png Screenshot from Atari 8-bit computer]
<pre>
13 is prime
997 is prime
1 is not prime
6 is not prime
120 is not prime
0 is not prime
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function isPrime(n:int):Boolean
{
if(n < 2) return false;
Line 321 ⟶ 442:
if(n % i == 0) return false;
return true;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">function Is_Prime(Item : Positive) return Boolean is
Result : Boolean := True;
Test : Natural;
begin
if Item /= 2 and Item mod 2 = 01 then
Result :=return False;
elsif Item = 2 then
return True;
elsif Item mod 2 = 0 then
return False;
else
Test := 3;
while Test <= Integer(Sqrt(Float(Item))) loop
if Item mod Test = 0 then
Result :=return False;
exit;
end if;
Test := Test + 2;
end loop;
end if;
return ResultTrue;
end Is_Prime;</langsyntaxhighlight>
 
<code>Sqrt</code> is made visible by a with / use clause on <code>Ada.Numerics.Elementary_Functions</code>.
 
With Ada 2012, the function can be made more compact as an expression function (but without loop optimized by skipping even numbers) :
<syntaxhighlight lang="ada">function Is_Prime(Item : Positive) return Boolean is
(Item /= 1 and then
(for all Test in 2..Integer(Sqrt(Float(Item))) => Item mod Test /= 0));</syntaxhighlight>
As an alternative, one can use the generic function Prime_Numbers.Is_Prime, as specified in [[Prime decomposition#Ada]], which also implements trial division.
<langsyntaxhighlight Adalang="ada">with Prime_Numbers;
 
procedure Test_Prime is
Line 356 ⟶ 486:
raise Program_Error with "Test_Prime failed!";
end if;
end Test_Prime;</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
{{works with|A60}}
<syntaxhighlight lang = "algol">
begin
 
boolean procedure isprime(n);
value n; integer n;
begin
comment - local procedure tests whether n is even;
boolean procedure even(n);
value n; integer n;
even := entier(n / 2) * 2 = n;
 
if n < 2 then
isprime := false
else if even(n) then
isprime := (n = 2)
else
begin
comment - check odd divisors up to sqrt(n);
integer i, limit;
boolean divisible;
i := 3;
limit := entier(sqrt(n));
divisible := false;
for i := i while i <= limit and not divisible do
begin
if entier(n / i) * i = n then
divisible := true;
i := i + 2
end;
isprime := if divisible then false else true;
end;
end;
 
comment - exercise the procedure;
integer i;
outstring(1,"Testing first 50 numbers for primality:\n");
for i := 1 step 1 until 50 do
if isprime(i) then
outinteger(1,i);
 
end
</syntaxhighlight>
{{out}}
<pre>
Testing first 50 numbers for primality:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
</pre>
 
=={{header|ALGOL 68}}==
Line 363 ⟶ 543:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
{{prelude/is_prime.a68}};
<langsyntaxhighlight lang="algol68">main:(
INT upb=100;
printf(($" The primes up to "g(-3)" are:"l$,upb));
Line 372 ⟶ 552:
OD;
printf($l$)
)</langsyntaxhighlight>
{{out}}
The primes up to 100 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
 
=={{header|ALGOL-M}}==
<syntaxhighlight lang="algol">
BEGIN
 
% RETURN P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
 
% RETURN INTEGER SQUARE ROOT OF N %
INTEGER FUNCTION ISQRT(N);
INTEGER N;
BEGIN
INTEGER R1, R2;
R1 := N;
R2 := 1;
WHILE R1 > R2 DO
BEGIN
R1 := (R1+R2) / 2;
R2 := N / R1;
END;
ISQRT := R1;
END;
 
% RETURN 1 IF N IS PRIME, OTHERWISE 0 %
INTEGER FUNCTION ISPRIME(N);
INTEGER N;
BEGIN
IF N = 2 THEN
ISPRIME := 1
ELSE IF (N < 2) OR (MOD(N,2) = 0) THEN
ISPRIME := 0
ELSE % TEST ODD NUMBERS UP TO SQRT OF N %
BEGIN
INTEGER I, LIMIT;
LIMIT := ISQRT(N);
I := 3;
WHILE I <= LIMIT AND MOD(N,I) <> 0 DO
I := I + 2;
ISPRIME := (IF I <= LIMIT THEN 0 ELSE 1);
END;
END;
 
% TEST FOR PRIMES IN RANGE 1 TO 50 %
INTEGER I;
WRITE("");
FOR I := 1 STEP 1 UNTIL 50 DO
BEGIN
IF ISPRIME(I)=1 THEN WRITEON(I," "); % WORKS FOR 80 COL SCREEN %
END;
 
END
</syntaxhighlight>
{{out}}
<pre>
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47
</pre>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">% returns true if n is prime, false otherwise %
% uses trial division %
logical procedure isPrime ( integer value n ) ;
Line 394 ⟶ 635:
end;
havePrime
end isPrime ;</langsyntaxhighlight>
Test program:
<langsyntaxhighlight lang="algolw">begin
logical procedure isPrime ( integer value n ) ; algol "isPrime" ;
for i := 0 until 32 do if isPrime( i ) then writeon( i_w := 1,s_w := 1, i )
end.</langsyntaxhighlight>
{{out}}
2 3 5 7 11 13 17 19 23 29 31
 
=={{header|ArturoAPL}}==
<syntaxhighlight lang="APL">prime ← 2=0+.=⍳|⊣</syntaxhighlight>
{{out}}
<syntaxhighlight lang="APL"> (⊢(/⍨)prime¨)⍳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</syntaxhighlight>
 
=={{header|AppleScript}}==
<lang arturo>prime: @(n){
 
if n=2 -> return true
<syntaxhighlight lang="applescript">on isPrime(n)
if n=3 -> return true
if [or (n <=1 n%2=0]3) ->then return false(n is 2)
if (n mod 2 is 0) then return false
repeat with i from 3 to (n ^ 0.5) div 1 by 2
if (n mod i is 0) then return false
end repeat
upper: [toNumber [sqrt [toReal n]]]
loop [rangeBy 3 upper 2] {
if n%&=0 -> return false
}
return true
end isPrime
}
 
-- Test code:
loop 1..20 {
set output to {}
print "isPrime(" + & + ")? = " + [prime &]
repeat with n from -7 to 100
}</lang>
if (isPrime(n)) then set end of output to n
end repeat
return output</syntaxhighlight>
 
Or eliminating multiples of 3 at the start as well as those of 2:
{{out}}
 
<syntaxhighlight lang="applescript">on isPrime(n)
<pre>isPrime(1)? = false
if (n < 4) then return (n > 1)
isPrime(2)? = true
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
isPrime(3)? = true
repeat with i from 5 to (n ^ 0.5) div 1 by 6
isPrime(4)? = false
if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
isPrime(5)? = true
end repeat
isPrime(6)? = false
isPrime(7)? = true
return true
isPrime(8)? = false
end isPrime(9)? = false
isPrime(10)? = false
isPrime(11)? = true
isPrime(12)? = false
isPrime(13)? = true
isPrime(14)? = false
isPrime(15)? = false
isPrime(16)? = false
isPrime(17)? = true
isPrime(18)? = false
isPrime(19)? = true
isPrime(20)? = false</pre>
 
-- Test code:
=={{header|ATS}}==
set output to {}
<lang ATS>(* ****** ****** *)
repeat with n from -7 to 100
//
if (isPrime(n)) then set end of output to n
#include
end repeat
"share/atspre_staload.hats"
return output</syntaxhighlight>
#include
 
"share/HATS/atspre_staload_libats_ML.hats"
{{output}}
//
<syntaxhighlight lang="applescript">{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}</syntaxhighlight>
#staload M = "libats/libc/SATS/math.sats"
 
//
=={{header|ARM Assembly}}==
(* ****** ****** *)
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
//
<syntaxhighlight lang ARM Assembly>
fun
/* ARM assembly Raspberry PI */
isqrt(n: intGte(0)): intGte(0) =
/* program testtrialprime.s */
$UNSAFE.cast($M.sqrt_double(g0i2f(n)))
 
//
/************************************/
fun
/* Constantes */
is_prime
/************************************/
(
/* for this file see task include a file in language ARM assembly*/
n : intGte(2)
.include "../constantes.inc"
) : bool =
 
(
//.include "../../ficmacros32.inc" @ for debugging developper
if
/************************************/
(n = 2)
/* Initialized data */
then true
/************************************/
else (
.data
if n % 2 = 0
szMessPrime: .asciz " is prime.\n"
then false
szMessNotPrime: .asciz " is not prime.\n"
else (1, (isqrt(n)+1)/2).forall()(lam i => n % (2*i+1) != 0)
szCarriageReturn: .asciz "\n"
) (* else *)
szMessStart: .asciz "Program 32 bits start.\n"
) (* end of [is_prime] *)
/************************************/
//
/* UnInitialized data */
(* ****** ****** *)</lang>
/************************************/
.bss
sZoneConv: .skip 24
/************************************/
/* code section */
/************************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
mov r0,#19
bl testPrime
ldr r0,iStart @ number
bl testPrime
ldr r0,iStart1 @ number
bl testPrime
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrsZoneConv: .int sZoneConv
 
iAdrszMessPrime: .int szMessPrime
iAdrszMessNotPrime: .int szMessNotPrime
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessStart: .int szMessStart
iStart: .int 2600002183
iStart1: .int 4124163031
/******************************************************************/
/* test if number is prime */
/******************************************************************/
/* r0 contains the number */
testPrime:
push {r1,r2,lr} @ save registers
mov r2,r0
ldr r1,iAdrsZoneConv
bl conversion10 @ decimal conversion
ldr r0,iAdrsZoneConv
bl affichageMess
mov r0,r2
bl isPrime
cmp r0,#0
beq 1f
ldr r0,iAdrszMessPrime
bl affichageMess
b 100f
1:
ldr r0,iAdrszMessNotPrime
bl affichageMess
100:
pop {r1,r2,pc} @ restaur registers
/******************************************************************/
/* test if number is prime */
/******************************************************************/
/* r0 contains the number */
/* r0 return 1 if prime else return 0 */
isPrime:
push {r4,lr} @ save registers
cmp r0,#1 @ <= 1 ?
movls r0,#0 @ not prime
bls 100f
cmp r0,#3 @ 2 and 3 prime
movls r0,#1
bls 100f
tst r0,#1 @ even ?
moveq r0,#0 @ not prime
beq 100f
mov r4,r0 @ save number
mov r1,#3 @ first divisor
1:
mov r0,r4 @ number
bl division
add r1,r1,#2 @ increment divisor
cmp r3,#0 @ remainder = zero ?
moveq r0,#0 @ not prime
beq 100f
cmp r1,r2 @ divisors<=quotient ?
ble 1b @ loop
mov r0,#1 @ return prime
 
100:
pop {r4,pc} @ restaur registers
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"
</syntaxhighlight>
{{Out}}
<pre>
Program 32 bits start.
19 is prime.
2600002183 is prime.
4124163031 is not prime.
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">isPrime?: function [n][
if n=2 -> return true
if n=3 -> return true
if or? n=<1 0=n%2 -> return false
high: to :integer sqrt n
loop high..2 .step: 3 'i [
if 0=n%i -> return false
]
 
return true
]
loop 1..20 'i [
print ["isPrime?" i "=" isPrime? i ]
]</syntaxhighlight>
 
{{out}}
 
<pre>isPrime? 1 = false
isPrime? 2 = true
isPrime? 3 = true
isPrime? 4 = false
isPrime? 5 = true
isPrime? 6 = false
isPrime? 7 = true
isPrime? 8 = false
isPrime? 9 = false
isPrime? 10 = false
isPrime? 11 = true
isPrime? 12 = false
isPrime? 13 = true
isPrime? 14 = false
isPrime? 15 = false
isPrime? 16 = false
isPrime? 17 = true
isPrime? 18 = false
isPrime? 19 = true
isPrime? 20 = false</pre>
 
=={{header|AutoHotkey}}==
[http://www.autohotkey.com/forum/topic44657.html Discussion]
<langsyntaxhighlight lang="autohotkey">MsgBox % IsPrime(1995937)
Loop
MsgBox % A_Index-3 . " is " . (IsPrime(A_Index-3) ? "" : "not ") . "prime."
Line 487 ⟶ 863:
d := k+(k<7 ? 1+(k>2) : SubStr("6-----4---2-4---2-4---6-----2",Mod(k,30),1))
Return n < 3 ? n>1 : Mod(n,k) ? (d*d <= n ? IsPrime(n,d) : 1) : 0
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight lang="autoit">#cs ----------------------------------------------------------------------------
 
AutoIt Version: 3.3.8.1
Line 523 ⟶ 899:
Return True
EndFunc
main()</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 530 ⟶ 906:
Or more legibly, and with n <= 1 handling
 
<langsyntaxhighlight AWKlang="awk">function prime(n) {
if (n <= 1) return 0
for (d = 2; d <= sqrt(n); d++)
Line 537 ⟶ 913:
}
 
{print prime($1)}</langsyntaxhighlight>
 
=={{header|B}}==
Line 543 ⟶ 919:
{{trans|C}}
{{works with|B as on PDP7/UNIX0|(proto-B?)}}
<langsyntaxhighlight Blang="b">isprime(n) {
auto p;
if(n<2) return(0);
Line 553 ⟶ 929:
}
return(1);
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="basic"> 100 DEF FN MOD(NUM) = NUM - INT (NUM / DIV) * DIV: REM NUM MOD DIV
Returns 1 for prime, 0 for non-prime
110 FOR I = 1 TO 99
<lang QBasic>FUNCTION prime% (n!)
120 V = I: GOSUB 200"ISPRIME
STATIC i AS INTEGER
130 IF n = 2 IF ISPRIME THEN PRINT " "I;
140 NEXT I
prime = 1
150 END
ELSEIF n <= 1 OR n MOD 2 = 0 THEN
prime = 0
200 ISPRIME = FALSE: IF V < 2 THEN RETURN
ELSE
210 DIV = 2:ISPRIME = FN MOD(V): IF NOT ISPRIME THEN ISPRIME = V = 2: RETURN
prime = 1
220 LIMIT = SQR (V): IF LIMIT > = 3 THEN FOR DIV = 3 TO LIMIT STEP 2:ISPRIME = FN MOD(V): IF ISPRIME THEN NEXT DIV
FOR i = 3 TO INT(SQR(n)) STEP 2
230 RETURN</syntaxhighlight>
IF n MOD i = 0 THEN
==={{header|BASIC256}}===
prime = 0
{{trans|FreeBASIC}}
EXIT FUNCTION
<syntaxhighlight lang="freebasic">for i = 1 to 99
END IF
if isPrime(i) then print string(i); " ";
NEXT i
next i
END IF
end
 
function isPrime(v)
if v < 2 then return False
if v mod 2 = 0 then return v = 2
if v mod 3 = 0 then return v = 3
d = 5
while d * d <= v
if v mod d = 0 then return False else d += 2
end while
return True
end function</syntaxhighlight>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> FOR i% = -1 TO 100
IF FNisprime(i%) PRINT ; i% " is prime"
NEXT
END
DEF FNisprime(n%)
IF n% <= 1 THEN = FALSE
IF n% <= 3 THEN = TRUE
IF (n% AND 1) = 0 THEN = FALSE
LOCAL t%
FOR t% = 3 TO SQR(n%) STEP 2
IF n% MOD t% = 0 THEN = FALSE
NEXT
= TRUE</syntaxhighlight>
{{out}}
<pre>2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime</pre>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">for i = 1 to 50
 
if i < 2 then
 
let p = 0
 
else
 
if i = 2 then
 
let p = 1
 
else
 
if i % 2 = 0 then
 
let p = 0
 
else
 
let p = 1
 
for j = 3 to int(i ^ .5) step 2
 
if i % j = 0 then
 
let p = 0
break j
 
endif
 
wait
 
next j
 
endif
 
endif
 
endif
 
if p <> 0 then
 
print i
 
endif
 
next i</syntaxhighlight>
{{out| Output}}<pre>2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 </pre>
 
==={{header|FBSL}}===
The second function (included by not used) I would have thought would be faster because it lacks the SQR() function. As it happens, the first is over twice as fast.
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
FUNCTION ISPRIME(n AS INTEGER) AS INTEGER
IF n = 2 THEN
RETURN TRUE
ELSEIF n <= 1 ORELSE n MOD 2 = 0 THEN
RETURN FALSE
ELSE
FOR DIM i = 3 TO SQR(n) STEP 2
IF n MOD i = 0 THEN
RETURN FALSE
END IF
NEXT
RETURN TRUE
END IF
END FUNCTION
 
FUNCTION ISPRIME2(N AS INTEGER) AS INTEGER
IF N <= 1 THEN RETURN FALSE
DIM I AS INTEGER = 2
WHILE I * I <= N
IF N MOD I = 0 THEN
RETURN FALSE
END IF
I = I + 1
WEND
RETURN TRUE
END FUNCTION
 
' Test and display primes 1 .. 50
DIM n AS INTEGER
DECLARE FUNCTION prime% (n!)
 
FOR n = 1 TO 50
IF primeISPRIME(n) = 1 THEN PRINT n;
PRINT n, " ";
NEXT n</lang>
END IF
NEXT
 
PAUSE</syntaxhighlight>
{{out}}
<pre>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Press any key to continue...
</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isPrime(n As Integer) As Boolean
If n < 2 Then Return False
If n = 2 Then Return True
If n Mod 2 = 0 Then Return False
Dim limit As Integer = Sqr(n)
For i As Integer = 3 To limit Step 2
If n Mod i = 0 Then Return False
Next
Return True
End Function
 
' To test this works, print all primes under 100
For i As Integer = 1 To 99
If isPrime(i) Then
Print Str(i); " ";
End If
Next
 
Print : Print
Print "Press any key to quit"
Sleep</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|FutureBasic}}===
<syntaxhighlight lang="futurebasic">window 1, @"Primality By Trial Division", (0,0,480,270)
 
local fn isPrime( n as long ) as Boolean
long i
Boolean result
if n < 2 then result = NO : exit fn
if n = 2 then result = YES : exit fn
if n mod 2 == 0 then result = NO : exit fn
result = YES
for i = 3 to int( n^.5 ) step 2
if n mod i == 0 then result = NO : break
next i
end fn = result
 
long i, j = 0
 
print "Prime numbers between 0 and 1000:"
for i = 0 to 1000
if ( fn isPrime(i) != _false )
printf @"%3d\t",i : j++
if j mod 10 == 0 then print
end if
next
 
HandleEvents</syntaxhighlight>
{{out}}
<pre>
Prime numbers between 0 and 1000:
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
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997
</pre>
 
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=85fbc7936b17b3009af282752aa29df7 Click this link to run this code]'''
<syntaxhighlight lang="gambas">'Reworked from the BBC Basic example
 
Public Sub Main()
Dim iNum As Integer
 
For iNum = 1 To 100
If FNisprime(iNum) Then Print iNum & " is prime"
Next
 
End
'___________________________________________________
Public Sub FNisprime(iNum As Integer) As Boolean
Dim iLoop As Integer
Dim bReturn As Boolean = True
 
If iNum <= 1 Then bReturn = False
If iNum <= 3 Then bReturn = True
If (iNum And 1) = 0 Then bReturn = False
 
For iLoop = 3 To Sqr(iNum) Step 2
If iNum Mod iLoop = 0 Then bReturn = False
Next
 
Return bReturn
 
End</syntaxhighlight>
{{out}}
<pre>1 is prime
3 is prime
5 is prime
7 is prime
11 is prime
......
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime</pre>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Prime.bas"
110 FOR X=0 TO 100
120 IF PRIME(X) THEN PRINT X;
Line 599 ⟶ 1,239:
230 NEXT
240 END IF
250 END DEF</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">print "Rosetta Code - Primality by trial division"
print
[start]
input "Enter an integer: "; x
if x=0 then print "Program complete.": end
if isPrime(x) then print x; " is prime" else print x; " is not prime"
goto [start]
 
function isPrime(p)
p=int(abs(p))
if p=2 then isPrime=1: exit function 'prime
if p=0 or p=1 or (p mod 2)=0 then exit function 'not prime
for i=3 to sqr(p) step 2
if (p mod i)=0 then exit function 'not prime
next i
isPrime=1
end function</syntaxhighlight>
{{out}}
<pre>Rosetta Code - Primality by trial division
 
Enter an integer: 1
1 is not prime
Enter an integer: 2
2 is prime
Enter an integer:
Program complete.</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Procedure.i IsPrime(n)
Protected k
 
If n = 2
ProcedureReturn #True
EndIf
 
If n <= 1 Or n % 2 = 0
ProcedureReturn #False
EndIf
For k = 3 To Int(Sqr(n)) Step 2
If n % k = 0
ProcedureReturn #False
EndIf
Next
 
ProcedureReturn #True
EndProcedure</syntaxhighlight>
 
==={{header|QuickBASIC}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
Returns 1 for prime, 0 for non-prime
<syntaxhighlight lang="qbasic">' Primality by trial division
 
' Test and display primes 1 .. 50
DECLARE FUNCTION prime% (n!)
FOR n = 1 TO 50
IF prime(n) = 1 THEN PRINT n;
NEXT n
 
FUNCTION prime% (n!)
STATIC i AS INTEGER
IF n = 2 THEN
prime = 1
ELSEIF n <= 1 OR n MOD 2 = 0 THEN
prime = 0
ELSE
prime = 1
FOR i = 3 TO INT(SQR(n)) STEP 2
IF n MOD i = 0 THEN
prime = 0
EXIT FUNCTION
END IF
NEXT i
END IF
END FUNCTION</syntaxhighlight>
{{out}}
<pre>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
</pre>
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="runbasic">' Test and display primes 1 .. 50
for i = 1 TO 50
if prime(i) <> 0 then print i;" ";
next i
 
FUNCTION prime(n)
if n < 2 then prime = 0 : goto [exit]
if n = 2 then prime = 1 : goto [exit]
if n mod 2 = 0 then prime = 0 : goto [exit]
prime = 1
for i = 3 to int(n^.5) step 2
if n mod i = 0 then prime = 0 : goto [exit]
next i
[exit]
END FUNCTION</syntaxhighlight>
{{out}}
<pre>
2 3 5 7 11 13 17 19 23 25 29 31 37 41 43 47
</pre>
 
==={{header|S-BASIC}}===
<syntaxhighlight lang="s-basic">
$lines
 
$constant FALSE = 0
$constant TRUE = 0FFFFH
 
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
 
rem - return true (-1) if n is prime, otherwise false (0)
function isprime(n = integer) = integer
var i, limit, result = integer
if n = 2 then
result = TRUE
else if (n < 2) or (mod(n,2) = 0) then
result = FALSE
else
begin
limit = int(sqr(n))
i = 3
while (i <= limit) and (mod(n, i) <> 0) do
i = i + 2
result = not (i <= limit)
end
end = result
 
rem - test by looking for primes in range 1 to 50
var i = integer
for i = 1 to 50
if isprime(i) then print using "#####";i;
next i
 
end
</syntaxhighlight>
{{out}}
<pre>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
</pre>
 
==={{header|TI-83 BASIC}}===
Prompt A
If A=2:Then
Disp "PRIME"
Stop
End
If (fPart(A/2)=0 and A>0) or A<2:Then
Disp "NOT PRIME"
Stop
End
1→P
For(B,3,int(√(A)))
If FPart(A/B)=0:Then
0→P
√(A)→B
End
B+1→B
End
If P=1:Then
Disp "PRIME"
Else
Disp "NOT PRIME"
End
 
==={{header|Tiny BASIC}}===
{{works with|TinyBasic}}
<syntaxhighlight lang="basic">10 REM Primality by trial division
20 PRINT "Enter a number "
30 INPUT P
40 GOSUB 1000
50 IF Z = 1 THEN PRINT "It is prime."
60 IF Z = 0 THEN PRINT "It is not prime."
70 END
 
990 REM Primality of the number P by trial division
1000 IF P < 2 THEN RETURN
1010 LET Z = 1
1020 IF P < 4 THEN RETURN
1030 LET I = 2
1040 IF (P / I) * I = P THEN LET Z = 0
1050 IF Z = 0 THEN RETURN
1060 LET I = I + 1
1070 IF I * I <= P THEN GOTO 1040
1080 RETURN</syntaxhighlight>
 
==={{header|True BASIC}}===
{{trans|QuickBASIC}}
<syntaxhighlight lang="qbasic">FUNCTION isPrime (n)
IF n = 2 THEN
LET isPrime = 1
ELSEIF n <= 1 OR REMAINDER(n, 2) = 0 THEN
LET isPrime = 0
ELSE
LET isPrime = 1
FOR i = 3 TO INT(SQR(n)) STEP 2
IF REMAINDER(n, i) = 0 THEN
LET isPrime = 0
EXIT FUNCTION
END IF
NEXT i
END IF
END FUNCTION
 
FOR n = 1 TO 50
IF isPrime(n) = 1 THEN PRINT n;
NEXT n
END</syntaxhighlight>
 
==={{header|uBasic/4tH}}===
<syntaxhighlight lang="text">10 LET n=0: LET p=0
20 INPUT "Enter number: ";n
30 LET p=0 : IF n>1 THEN GOSUB 1000
40 IF p=0 THEN PRINT n;" is not prime!"
50 IF p#0 THEN PRINT n;" is prime!"
60 GOTO 10
1000 REM ***************
1001 REM * PRIME CHECK *
1002 REM ***************
1010 LET p=0
1020 IF (n%2)=0 THEN RETURN
1030 LET p=1 : PUSH n,0 : GOSUB 9030
1040 FOR i=3 TO POP() STEP 2
1050 IF (n%i)=0 THEN LET p=0: PUSH n,0 : GOSUB 9030 : LET i=POP()
1060 NEXT i
1070 RETURN
9030 Push ((10^(Pop()*2))*Pop()) : @(255)=Tos()
9040 Push (@(255) + (Tos()/@(255)))/2
If Abs(@(255)-Tos())<2 Then @(255)=Pop() : If Pop() Then Push @(255) : Return
@(255) = Pop() : Goto 9040
REM ** This is an integer SQR subroutine. Output is scaled by 10^(TOS()).</syntaxhighlight>
 
==={{header|VBA}}===
<syntaxhighlight lang="vb">Option Explicit
 
Sub FirstTwentyPrimes()
Dim count As Integer, i As Long, t(19) As String
Do
i = i + 1
If IsPrime(i) Then
t(count) = i
count = count + 1
End If
Loop While count <= UBound(t)
Debug.Print Join(t, ", ")
End Sub
 
Function IsPrime(Nb As Long) As Boolean
If Nb = 2 Then
IsPrime = True
ElseIf Nb < 2 Or Nb Mod 2 = 0 Then
Exit Function
Else
Dim i As Long
For i = 3 To Sqr(Nb) Step 2
If Nb Mod i = 0 Then Exit Function
Next
IsPrime = True
End If
End Function</syntaxhighlight>
{{out}}
<pre>
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
</pre>
 
==={{header|VBScript}}===
{{trans|QuickBASIC}}
<syntaxhighlight lang="vb">Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
 
For n = 1 To 50
If IsPrime(n) Then
WScript.StdOut.Write n & " "
End If
Next</syntaxhighlight>
{{out}}
<pre>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
</pre>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">for i = 1 to 99
if isPrime(i) print str$(i), " ";
next i
print
end
 
sub isPrime(v)
if v < 2 return False
if mod(v, 2) = 0 return v = 2
if mod(v, 3) = 0 return v = 3
d = 5
while d * d <= v
if mod(v, d) = 0 then return False else d = d + 2 : fi
wend
return True
end sub</syntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
<langsyntaxhighlight ZXBasiclang="zxbasic">10 LET n=0: LET p=0
20 INPUT "Enter number: ";n
30 IF n>1 THEN GO SUB 1000
Line 618 ⟶ 1,578:
1060 NEXT i
1070 RETURN
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 625 ⟶ 1,585:
119 is not prime!
137 is prime!</pre>
 
=={{header|BBC BASIC}}==
<lang bbcbasic> FOR i% = -1 TO 100
IF FNisprime(i%) PRINT ; i% " is prime"
NEXT
END
DEF FNisprime(n%)
IF n% <= 1 THEN = FALSE
IF n% <= 3 THEN = TRUE
IF (n% AND 1) = 0 THEN = FALSE
LOCAL t%
FOR t% = 3 TO SQR(n%) STEP 2
IF n% MOD t% = 0 THEN = FALSE
NEXT
= TRUE</lang>
{{out}}
<pre>2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime</pre>
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">/* Return 1 if n is prime, 0 otherwise */
define p(n) {
auto i
Line 680 ⟶ 1,598:
}
return(1)
}</langsyntaxhighlight>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let sqrt(s) =
s <= 1 -> 1,
valof
$( let x0 = s >> 1
let x1 = (x0 + s/x0) >> 1
while x1 < x0
$( x0 := x1
x1 := (x0 + s/x0) >> 1
$)
resultis x0
$)
 
let isprime(n) =
n < 2 -> false,
(n & 1) = 0 -> n = 2,
valof
$( for i = 3 to sqrt(n) by 2
if n rem i = 0 resultis false
resultis true
$)
 
let start() be
$( for i=1 to 100
if isprime(i) then writef("%N ",i)
wrch('*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</pre>
 
=={{header|Befunge}}==
Line 687 ⟶ 1,637:
To avoid dealing with Befunge's limited data cells, the implementation is entirely stack-based. However, this requires compressing multiple values into a single stack cell, which imposes an upper limit of 1,046,529 (1023<sup>2</sup>), thus a maximum testable prime of 1,046,527.
 
<langsyntaxhighlight lang="befunge">&>:48*:** \1`!#^_2v
v_v#`\*:%*:*84\/*:*84::+<
v >::48*:*/\48*:*%%!#v_1^
>0"seY" >:#,_@#: "No">#0<</langsyntaxhighlight>
 
{{out}} (multiple runs)
Line 707 ⟶ 1,657:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat"> ( prime
= incs n I inc
. 4 2 4 2 4 6 2 6:?incs
Line 728 ⟶ 1,678:
)
)
& ;</langsyntaxhighlight>
{{out}}
<pre>100000000003
Line 737 ⟶ 1,687:
100000000073
100000000091</pre>
 
=={{header|Brainf***}}==
<syntaxhighlight lang="bf">>->,[.>,]>-<++++++[-<+[---------<+]->+[->+]-<]>+<-<+[-<+]>>+[-<[->++++++++++<]>>
+]++++[->++++++++<]>.<+++++++[->++++++++++<]>+++.++++++++++.<+++++++++[->-------
--<]>--.[-]<<<->[->+>+<<]>>-[+<[[->>+>>+<<<<]>>[-<<+>>]<]>>[->-[>+>>]>[+[-<+>]>>
>]<<<<<]>[-]>[>+>]<<[-]+[-<+]->>>--]<[->+>+<<]>>>>>>>[-<<<<<->>>>>]<<<<<--[>++++
++++++[->+++++++++++<]>.+.+++++.>++++[->++++++++<]>.>]++++++++++[->+++++++++++<]
>++.++.---------.++++.--------.>++++++++++.</syntaxhighlight>
Explanation:
<syntaxhighlight lang="bf">>
->,[.>,]>-<++++++[-<+[---------<+]->+[->+]-<]>+<-<+[-<+]>>+[-<[->++++++++++<]>>+]< takes input
>++++[->++++++++<]>.<+++++++[->++++++++++<]>+++.++++++++++.<+++++++++[->---------<]>--.[-]<< " is "
<->
[->+>+<<]>>-[+<[[->>+>>+<<<<]>>[-<<+>>]<]>>[->-[>+>>]>[+[-<+>]>>>]<<<<<]>[-]>[>+>]<<[-]+[-<+]->>>--] finds # of divisors from 1 to n
<[->+>+<<]>>>>>>>[-<<<<<->>>>>]<<<<<--
[>++++++++++[->+++++++++++<]>.+.+++++.>++++[->++++++++<]>.>] "not "
++++++++++[->+++++++++++<]>++.++.---------.++++.--------.>++++++++++. "prime" new line</syntaxhighlight>
Will format as "# is/is not prime", naturally limited by cell size.
 
=={{header|Burlesque}}==
<langsyntaxhighlight lang="burlesque">fcL[2==</langsyntaxhighlight>
 
Implicit trial division is done by the ''fc'' function. It checks if the number has exactly two divisors.
Line 745 ⟶ 1,713:
Version not using the ''fc'' function:
 
<langsyntaxhighlight lang="burlesque">blsq ) 11^^2\/?dr@.%{0==}ayn!
1
blsq ) 12^^2\/?dr@.%{0==}ayn!
0
blsq ) 13^^2\/?dr@.%{0==}ayn!
1</langsyntaxhighlight>
Explanation. Given ''n'' generates a block containing ''2..n-1''. Calculates a block of modolus and check if it contains ''0''. If it contains ''0''
it is not a prime.
 
=={{header|C}}==
<langsyntaxhighlight lang="c">int is_prime(unsigned int n)
{
unsigned int p;
Line 764 ⟶ 1,732:
if (!(n % p)) return 0;
return 1;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">static bool isPrime(int n)
{
if (n <= 1) return false;
Line 773 ⟶ 1,741:
if (n % i == 0) return false;
return true;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <cmath>
 
bool is_prime(unsigned int n)
Line 788 ⟶ 1,756:
return false;
return true;
}</langsyntaxhighlight>
 
=={{header|Chapel}}==
{{trans|C++}}
<langsyntaxhighlight lang="chapel">proc is_prime(n)
{
if n == 2 then
Line 802 ⟶ 1,770:
return false;
return true;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
The function used in both versions:
<langsyntaxhighlight lang="clojure">(defn divides? [k n] (zero? (mod k n)))</langsyntaxhighlight>
 
Testing divisors are in range from '''3''' to '''&radic;{{overline|&nbsp;n&nbsp;}} &nbsp;''' with step '''2''':
<langsyntaxhighlight lang="clojure">(defn prime? [x]
(or (= 2 x)
(and (< 1 x)
Line 815 ⟶ 1,783:
(not-any? (partial divides? x)
(range 3 (inc (Math/sqrt x)) 2)))))
</syntaxhighlight>
</lang>
 
Testing only prime divisors:
<langsyntaxhighlight lang="clojure">(declare prime?)
 
(def primes (filter prime? (range)))
Line 827 ⟶ 1,795:
(not-any? (partial divides? x)
(take-while (partial >= (Math/sqrt x)) primes))))
</syntaxhighlight>
</lang>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">isqrt = proc (s: int) returns (int)
x0: int := s/2
if x0=0 then return(s) end
x1: int := (x0 + s/x0)/2
while x1 < x0 do
x0 := x1
x1 := (x0 + s/x0)/2
end
return(x0)
end isqrt
 
prime = proc (n: int) returns (bool)
if n<=2 then return(n=2) end
if n//2=0 then return(false) end
for d: int in int$from_to_by(3,isqrt(n),2) do
if n//d=0 then return(false) end
end
return(true)
end prime
 
start_up = proc ()
po: stream := stream$primary_input()
for i: int in int$from_to(1,100) do
if prime(i) then
stream$puts(po, int$unparse(i) || " ")
end
end
end start_up</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|CMake}}==
<langsyntaxhighlight lang="cmake"># Prime predicate: does n be a prime number? Sets var to true or false.
function(primep var n)
if(n GREATER 2)
Line 860 ⟶ 1,860:
set(${var} false PARENT_SCOPE) # n < 2 is not prime.
endif()
endfunction(primep)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="cmake"># Quick example.
foreach(i -5 1 2 3 37 39)
primep(b ${i})
Line 870 ⟶ 1,870:
message(STATUS "${i} is _not_ prime.")
endif(b)
endforeach(i)</langsyntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> Identification Division.
Program-Id. Primality-By-Subdiv.
 
Line 910 ⟶ 1,910:
 
Goback
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">is_prime = (n) ->
# simple prime detection using trial division, works
# for all integers
Line 924 ⟶ 1,924:
for i in [-1..100]
console.log i if is_prime i</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight Lisplang="lisp">(defun primep (n)
"Is N prime?"
(and (> n 1)
(or (= n 2) (oddp n))
(loop for i from 3 to (isqrt n) by 2
never (zerop (rem n i)))))</langsyntaxhighlight>
===Alternate solution===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
 
<langsyntaxhighlight lang="lisp">;; Project : Primality by trial division
 
(defun prime(n)
Line 947 ⟶ 1,947:
(format t "~d is not a prime number" n)))
(prime 7)
(prime 8)</langsyntaxhighlight>
Output:
7 is a prime number
8 is not a prime number
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub prime(n: uint32): (isprime: uint8) is
isprime := 1;
 
if n < 2 then
isprime := 0;
return;
end if;
 
if n & 1 == 0 then
if n != 2 then
isprime := 0;
end if;
return;
end if;
 
var factor: uint32 := 3;
while factor * factor <= n loop
if n % factor == 0 then
isprime := 0;
return;
end if;
factor := factor + 2;
end loop;
end sub;
 
var i: uint32 := 0;
while i <= 100 loop
if prime(i) != 0 then
print_i32(i);
print_nl();
end if;
i := i + 1;
end loop;</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|Crystal}}==
Mathematicaly basis of Prime Generators
https://www.academia.edu/19786419/PRIMES-UTILS_HANDBOOK
https://www.academia.edu/42734410/Improved_Primality_Testing_and_Factorization_in_Ruby_revised
<syntaxhighlight lang="ruby">require "big"
require "benchmark"
 
# the simplest PG primality test using the P3 prime generator
# reduces the number space for primes to 2/6 (33.33%) of all integers
 
def primep3?(n) # P3 Prime Generator primality test
# P3 = 6*k + {5, 7} # P3 primes candidates (pc) sequence
n = n.to_big_i
return n | 1 == 3 if n < 5 # n: 0,1,4|false, 2,3|true
return false if n.gcd(6) != 1 # 1/3 (2/6) of integers are P3 pc
p = typeof(n).new(5) # first P3 sequence value
until p > isqrt(n)
return false if n % p == 0 || n % (p + 2) == 0 # if n is composite
p += 6 # first prime candidate for next kth residues group
end
true
end
 
# PG primality test using the P5 prime generator
# reduces the number space for primes to 8/30 (26.67%) of all integers
 
def primep5?(n) # P5 Prime Generator primality test
# P5 = 30*k + {7,11,13,17,19,23,29,31} # P5 primes candidates sequence
n = n.to_big_i
return [2, 3, 5].includes?(n) if n < 7 # for small and negative values
return false if n.gcd(30) != 1 # 4/15 (8/30) of integers are P5 pc
p = typeof(n).new(7) # first P5 sequence value
until p > isqrt(n)
return false if # if n is composite
n % (p) == 0 || n % (p+4) == 0 || n % (p+6) == 0 || n % (p+10) == 0 ||
n % (p+12) == 0 || n % (p+16) == 0 || n % (p+22) == 0 || n % (p+24) == 0
p += 30 # first prime candidate for next kth residues group
end
true
end
 
# PG primality test using the P7 prime generator
# reduces the number space for primes to 48/210 (22.86%) of all integers
 
def primep7?(n)
# P7 = 210*k + {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,121,127,131,137,139,143,149,151,157,163,
# 167,169,173,179,181,187,191,193,197,199,209,211}
n = n.to_big_i
return [2, 3, 5, 7].includes?(n) if n < 11
return false if n.gcd(210) != 1 # 8/35 (48/210) of integers are P7 pc
p = typeof(n).new(11) # first P7 sequence value
until p > isqrt(n)
return false if
n % (p) == 0 || n % (p+2) == 0 || n % (p+6) == 0 || n % (p+8) == 0 ||
n % (p+12) == 0 || n % (p+18) == 0 || n % (p+20) == 0 || n % (p+26) == 0 ||
n % (p+30) == 0 || n % (p+32) == 0 || n % (p+36) == 0 || n % (p+42) == 0 ||
n % (p+48) == 0 || n % (p+50) == 0 || n % (p+56) == 0 || n % (p+60) == 0 ||
n % (p+62) == 0 || n % (p+68) == 0 || n % (p+72) == 0 || n % (p+78) == 0 ||
n % (p+86) == 0 || n % (p+90) == 0 || n % (p+92) == 0 || n % (p+96) == 0 ||
n % (p+98) == 0 || n % (p+102) == 0 || n % (p+110) == 0 || n % (p+116) == 0 ||
n % (p+120) == 0 || n % (p+126) == 0 || n % (p+128) == 0 || n % (p+132) == 0 ||
n % (p+138) == 0 || n % (p+140) == 0 || n % (p+146) == 0 || n % (p+152) == 0 ||
n % (p+156) == 0 || n % (p+158) == 0 || n % (p+162) == 0 || n % (p+168) == 0 ||
n % (p+170) == 0 || n % (p+176) == 0 || n % (p+180) == 0 || n % (p+182) == 0 ||
n % (p+186) == 0 || n % (p+188) == 0 || n % (p+198) == 0 || n % (p+200) == 0
p += 210 # first prime candidate for next kth residues group
end
true
end
 
# Newton's method for integer squareroot
def isqrt(n)
raise ArgumentError.new "Input must be non-negative integer" if n < 0
return n if n < 2
bits = n.bit_length
one = typeof(n).new(1) # value 1 of type self
x = one << ((bits - 1) >> 1) | n >> ((bits >> 1) + 1)
while (t = n // x) < x; x = (x + t) >> 1 end
x # output is same integer class as input
end
 
# Benchmarks to test for various size primes
 
p = 541
Benchmark.ips do |b|
print "\np = #{p}"
b.report("primep3?") { primep3?(p) }
b.report("primep5?") { primep5?(p) }
b.report("primep7?") { primep7?(p) }
puts
end
 
p = 1000003
Benchmark.ips do |b|
print "\np = #{p}"
b.report("primep3?") { primep3?(p) }
b.report("primep5?") { primep5?(p) }
b.report("primep7?") { primep7?(p) }
puts
end
 
p = 2147483647i32 # largest I32 prime
Benchmark.ips do |b|
print "\np = #{p}"
b.report("primep3?") { primep3?(p) }
b.report("primep5?") { primep5?(p) }
b.report("primep7?") { primep7?(p) }
puts
end
 
p = 4294967291u32 # largest U32 prime
Benchmark.ips do |b|
print "\np = #{p}"
b.report("primep3?") { primep3?(p) }
b.report("primep5?") { primep5?(p) }
b.report("primep7?") { primep7?(p) }
puts
end
 
p = 4294967311 # first prime > 2**32
Benchmark.ips do |b|
print "\np = #{p}"
b.report("primep3?") { primep3?(p) }
b.report("primep5?") { primep5?(p) }
b.report("primep7?") { primep7?(p) }
puts
end</syntaxhighlight>
{{out}}
<pre>p = 541
primep3? 290.17k ( 3.45µs) (± 2.76%) 1.35kB/op 1.64× slower
primep5? 476.47k ( 2.10µs) (± 1.75%) 802B/op fastest
primep7? 128.44k ( 7.79µs) (± 2.82%) 2.66kB/op 3.71× slower
 
p = 1000003
primep3? 11.24k ( 88.97µs) (± 2.34%) 33.9kB/op 2.48× slower
primep5? 21.91k ( 45.64µs) (± 2.88%) 16.6kB/op 1.27× slower
primep7? 27.83k ( 35.94µs) (± 2.68%) 11.9kB/op fastest
 
p = 2147483647
primep3? 105.11 ( 9.51ms) (± 3.25%) 3.89MB/op 5.56× slower
primep5? 317.49 ( 3.15ms) (± 2.40%) 1.2MB/op 1.84× slower
primep7? 584.92 ( 1.71ms) (± 3.09%) 591kB/op fastest
 
p = 4294967291
primep3? 168.56 ( 5.93ms) (± 2.39%) 2.17MB/op 2.69× slower
primep5? 349.24 ( 2.86ms) (± 2.86%) 1.03MB/op 1.30× slower
primep7? 454.08 ( 2.20ms) (± 2.62%) 739kB/op fastest
 
p = 4294967311
primep3? 84.61 ( 11.82ms) (± 2.35%) 4.68MB/op 5.02× slower
primep5? 248.62 ( 4.02ms) (± 2.21%) 1.54MB/op 1.71× slower
primep7? 424.61 ( 2.36ms) (± 2.73%) 813kB/op fastest
</pre>
 
=={{header|D}}==
===Simple Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.math;
 
bool isPrime1(T)(in intT n) pure nothrow {
if (n == 2)
return true;
if (n <= 1 || (n & 1) == 0)
return false;
 
for(intT i = 3; i <= real(n).sqrt; i += 2)
if (n % i == 0)
return false;
return true;
}
 
 
void main() {
iota(2, 40).filter!isPrime1.writeln;
}</langsyntaxhighlight>
{{out}}
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
 
===Version with excluded multiplies of 2 and 3===
Same output.
<langsyntaxhighlight lang="d">bool isPrime2(It)(in It n) pure nothrow {
// Adapted from: http://www.devx.com/vb2themax/Tip/19051
// Test 1, 2, 3 and multiples of 2 and 3:
Line 999 ⟶ 2,221:
 
iota(2, 40).filter!isPrime2.writeln;
}</langsyntaxhighlight>
 
===Two Way Test===
Odd divisors is generated both from increasing and decreasing sequence, may improve performance for numbers that have large minimum factor.
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.math;
 
bool isPrime3(T)(in T n) pure nothrow {
Line 1,018 ⟶ 2,240:
void main() {
iota(2, 40).filter!isPrime3.writeln;
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">import 'dart:math';
 
bool isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
for (int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false;
return true;
}
 
void main() {
for (int i = 1; i <= 99; ++i) if (isPrime(i)) print('$i ');
}</syntaxhighlight>
 
=={{header|Delphi}}==
=== First ===
<langsyntaxhighlight Delphilang="delphi">function IsPrime(aNumber: Integer): Boolean;
var
I: Integer;
Line 1,039 ⟶ 2,275:
Break;
end;
end;</langsyntaxhighlight>
 
=== Second ===
<langsyntaxhighlight Delphilang="delphi">function IsPrime(const x: integer): Boolean;
var
i: integer;
Line 1,056 ⟶ 2,292:
until i > Sqrt(x);
Result := True;
end;</langsyntaxhighlight>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc prime(word n) bool:
word factor;
bool composite;
if n<=4 then
n=2 or n=3
elif n&1 = 0 then
false
else
factor := 3;
composite := false;
while not composite and factor*factor <= n do
composite := n % factor = 0;
factor := factor + 2
od;
not composite
fi
corp
 
proc main() void:
word i;
for i from 0 upto 100 do
if prime(i) then
writeln(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|E}}==
{{trans|D}}
<langsyntaxhighlight lang="e">def isPrime(n :int) {
if (n == 2) {
return true
Line 1,075 ⟶ 2,365:
return true
}
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
func isprim n .
if n < 2
return 0
.
if n mod 2 = 0 and n > 2
return 0
.
i = 3
sq = sqrt n
while i <= sq
if n mod i = 0
return 0
.
i += 2
.
return 1
.
print isprim 1995937
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">(lib 'sequences)
 
;; Try divisors iff n = 2k + 1
Line 1,105 ⟶ 2,417:
(filter is-prime? (range 1 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)</langsyntaxhighlight>
 
=={{header|Eiffel}}==
<langsyntaxhighlight Eiffellang="eiffel">class
APPLICATION
 
Line 1,163 ⟶ 2,475:
end
 
end</langsyntaxhighlight>
<pre>False
True
Line 1,173 ⟶ 2,485:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def is_prime(2), do: true
def is_prime(n) when n<2 or rem(n,2)==0, do: false
Line 1,183 ⟶ 2,495:
end
 
IO.inspect for n <- 1..50, RC.is_prime(n), do: n</langsyntaxhighlight>
{{out}}
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
 
=={{header|Emacs Lisp}}==
{{libheader|cl-lib}}
Use <tt>cl.el</tt> library.
<langsyntaxhighlight lang="lisp">(defun prime (a)
(not (or (< a 2)
(cl-loop for x from 2 to (sqrt a)
when (zerop (% a x))
return t))))</langsyntaxhighlight>
 
More concise, a little bit faster:
<langsyntaxhighlight lang="lisp">(defun prime2 (a)
(and (> a 1)
(cl-loop for x from 2 to (sqrt a)
never (zerop (% a x)))))</langsyntaxhighlight>
 
A little bit faster:
<langsyntaxhighlight lang="lisp">(defun prime3 (a)
(and (> a 1)
(or (= a 2) (cl-oddp a))
(cl-loop for x from 3 to (sqrt a) by 2
never (zerop (% a x)))))</langsyntaxhighlight>
 
More than 2 times faster, than the previous, doesn't use <tt>loop</tt> macro:
<langsyntaxhighlight lang="lisp">(defun prime4 (a)
(not (or (< a 2)
(cl-some (lambda (x) (zerop (% a x))) (number-sequence 2 (sqrt a))))))</langsyntaxhighlight>
 
Almost 2 times faster, than the previous:
<langsyntaxhighlight lang="lisp">(defun prime5 (a)
(not (or (< a 2)
(and (/= a 2) (cl-evenp a))
(cl-some (lambda (x) (zerop (% a x))) (number-sequence 3 (sqrt a) 2)))))</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">is_prime(N) when N == 2 -> true;
is_prime(N) when N < 2 orelse N rem 2 == 0 -> false;
is_prime(N) -> is_prime(N,3).
Line 1,222 ⟶ 2,538:
is_prime(N,K) when K*K > N -> true;
is_prime(N,K) when N rem K == 0 -> false;
is_prime(N,K) -> is_prime(N,K+2).</langsyntaxhighlight>
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM PRIME_TRIAL
 
PROCEDURE ISPRIME(N%->OK%)
Line 1,245 ⟶ 2,561:
END FOR
 
END PROGRAM</langsyntaxhighlight>
{{out}}
2 is prime
Line 1,274 ⟶ 2,590:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function is_prime(integer n)
if n<=2 or remainder(n,2)=0 then
return 0
Line 1,285 ⟶ 2,601:
return 1
end if
end function</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open NUnit.Framework
open FsUnit
let inline isPrime n = not ({uint64 2..uint64 (sqrt (double n))} |> Seq.exists (fun (i:uint64) -> uint64 n % i = uint64 0))
Line 1,313 ⟶ 2,629:
[<Test>]
let ``Validate that 277 is prime`` () =
isPrime 277 |> should equal true</langsyntaxhighlight>
{{out}}
> isPrime 1111111111111111111UL;;
Line 1,319 ⟶ 2,635:
 
and if you want to test really big numbers, use System.Numerics.BigInteger, but it's slower:
<langsyntaxhighlight lang="fsharp">
let isPrimeI x =
if x < 2I then false else
Line 1,326 ⟶ 2,642:
let rec test n =
if n * n > x then true else
if x % n = 0I then false else test (n + 2I) in test 3I</langsyntaxhighlight>
 
If you have a lot of prime numbers to test, caching a sequence of primes can speed things up considerably, so you only have to do the divisions against prime numbers.
<langsyntaxhighlight lang="fsharp">let rec primes = Seq.cache(Seq.append (seq[ 2; 3; 5 ]) (Seq.unfold (fun state -> Some(state, state + 2)) 7 |> Seq.filter (fun x -> IsPrime x)))
and IsPrime number =
Line 1,346 ⟶ 2,662:
false
else
IsPrimeCore number 0 number</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators kernel math math.functions math.ranges sequences ;
 
: prime? ( n -- ? )
Line 1,356 ⟶ 2,672:
{ [ dup even? ] [ 2 = ] }
[ 3 over sqrt 2 <range> [ mod 0 > ] with all? ]
} cond ;</langsyntaxhighlight>
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[0\$2=$[@~@@]?~[$$2>\1&&[\~\
3[\$@$@1+\$*>][\$@$@$@$@\/*=[%\~\$]?2+]#%
]?]?%]p:</langsyntaxhighlight>
 
=={{header|FBSL}}==
The second function (included by not used) I would have thought would be faster because it lacks the SQR() function. As it happens, the first is over twice as fast.
<lang qbasic>#APPTYPE CONSOLE
 
FUNCTION ISPRIME(n AS INTEGER) AS INTEGER
IF n = 2 THEN
RETURN TRUE
ELSEIF n <= 1 ORELSE n MOD 2 = 0 THEN
RETURN FALSE
ELSE
FOR DIM i = 3 TO SQR(n) STEP 2
IF n MOD i = 0 THEN
RETURN FALSE
END IF
NEXT
RETURN TRUE
END IF
END FUNCTION
 
FUNCTION ISPRIME2(N AS INTEGER) AS INTEGER
IF N <= 1 THEN RETURN FALSE
DIM I AS INTEGER = 2
WHILE I * I <= N
IF N MOD I = 0 THEN
RETURN FALSE
END IF
I = I + 1
WEND
RETURN TRUE
END FUNCTION
 
' Test and display primes 1 .. 50
DIM n AS INTEGER
 
FOR n = 1 TO 50
IF ISPRIME(n) THEN
PRINT n, " ";
END IF
NEXT
 
PAUSE</lang>
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Press any key to continue...
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">: prime? ( n -- f )
 
<lang forth>: prime? ( n -- f )
dup 2 < if drop false
else dup 2 = if drop true
Line 1,420 ⟶ 2,691:
then 2 +
repeat 2drop true
then then then ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran"> FUNCTION isPrime(number)
LOGICAL :: isPrime
INTEGER, INTENT(IN) :: number
Line 1,442 ⟶ 2,713:
END DO
END IF
END FUNCTION</langsyntaxhighlight>
 
=={{header|FreeBASICFrink}}==
It is unnecessary to write this function because Frink has an efficient <CODE>isPrime[x]</CODE> function to test primality of arbitrarily-large integers. Here is a version that works for arbitrarily-large integers. Beware some of these solutions that calculate up to <CODE>sqrt[x]</CODE> but because of floating-point error the square root is slightly smaller than the true square root!
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="frink">isPrimeByTrialDivision[x] :=
 
{
Function isPrime(n As Integer) As Boolean
for p = primes[]
If n < 2 Then Return False
{
If n = 2 Then Return True
If n Mod 2 if =p*p 0> Then Return Falsex
return true
Dim limit As Integer = Sqr(n)
For i As Integer =if 3x Tomod limitp Step== 20
If n Mod i = 0return Then Return Falsefalse
Next }
Return True
return true
End Function
}</syntaxhighlight>
 
' To test this works, print all primes under 100
For i As Integer = 1 To 99
If isPrime(i) Then
Print Str(i); " ";
End If
Next
 
Print : Print
Print "Press any key to quit"
Sleep</lang>
 
{{out}}
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
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import math.sqrt
 
def
Line 1,481 ⟶ 2,739:
| otherwise = (3..int(sqrt(n)) by 2).forall( (/|n) )
 
(10^10..10^10+50).filter( isPrime ).foreach( println )</langsyntaxhighlight>
{{out}}
10000000019
10000000033
 
=={{header|FutureBasic}}==
<lang futurebasic>include "ConsoleWindow"
 
def tab 6
 
local fn isPrime( n as long ) as Boolean
dim as long i
dim as Boolean result
 
if n < 2 then result = _false : exit fn
if n = 2 then result = _true : exit fn
if n mod 2 == 0 then result = _false : exit fn
result = _true
for i = 3 to int( n^.5 ) step 2
if n mod i == 0 then result = _false : exit fn
next i
end fn = result
 
dim as long i, j
 
print "Prime numbers between 0 and 1000:"
for i = 0 to 1000
if ( fn isPrime(i) != _false )
print i, : j++
if j mod 10 == 0 then print
end if
next</lang>
Output:
Prime numbers between 0 and 1000:
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
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=85fbc7936b17b3009af282752aa29df7 Click this link to run this code]'''
<lang gambas>'Reworked from the BBC Basic example
 
Public Sub Main()
Dim iNum As Integer
 
For iNum = 1 To 100
If FNisprime(iNum) Then Print iNum & " is prime"
Next
 
End
'___________________________________________________
Public Sub FNisprime(iNum As Integer) As Boolean
Dim iLoop As Integer
Dim bReturn As Boolean = True
 
If iNum <= 1 Then bReturn = False
If iNum <= 3 Then bReturn = True
If (iNum And 1) = 0 Then bReturn = False
 
For iLoop = 3 To Sqr(iNum) Step 2
If iNum Mod iLoop = 0 Then bReturn = False
Next
 
Return bReturn
 
End</lang>
Output:
<pre>1 is prime
3 is prime
5 is prime
7 is prime
11 is prime
......
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">IsPrimeTrial := function(n)
local k, m;
if n < 5 then
Line 1,595 ⟶ 2,767:
 
Filtered([1 .. 100], IsPrimeTrial);
# [ 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 ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">func IsPrime(n int) bool {
if n < 0 { n = -n }
switch {
Line 1,612 ⟶ 2,784:
}
return true
}</langsyntaxhighlight>
 
Or, using recursion:
 
<langsyntaxhighlight lang="go">func IsPrime(n int) bool {
if n < 0 { n = -n }
if n <= 2 {
Line 1,629 ⟶ 2,801:
}
return true
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def isPrime = {
it == 2 ||
it > 1 &&
Line 1,638 ⟶ 2,810:
}
 
(0..20).grep(isPrime)</langsyntaxhighlight>
{{out}}
[2, 3, 5, 7, 11, 13, 17, 19]
Line 1,644 ⟶ 2,816:
=={{header|Haskell}}==
(used [[Emirp_primes#List-based|here]] and [[Sequence_of_primes_by_Trial_Division#Haskell|here]]). The basic divisibility test by odd numbers:
<langsyntaxhighlight lang="haskell">isPrime n = n==2 || n>2 && all ((> 0).rem n) (2:[3,5..floor.sqrt.fromIntegral $ n+1])</langsyntaxhighlight>
 
Testing by prime numbers only is faster. Primes list is saved for reuse. Precalculation of primes pays off if testing more than just a few numbers, and/or primes are generated efficiently enough:
<langsyntaxhighlight lang="haskell">noDivsBy factors n = foldr (\f r-> f*f>n || ((rem n f /= 0) && r)) True factors
 
-- primeNums = filter (noDivsBy [2..]) [2..]
Line 1,653 ⟶ 2,825:
primeNums = 2 : 3 : filter (noDivsBy $ tail primeNums) [5,7..]
 
isPrime n = n > 1 && noDivsBy primeNums n</langsyntaxhighlight>
Any increasing ''unbounded'' sequence of numbers that includes all primes (above the first few, perhaps) could be used with the testing function <code>noDivsBy</code> to define the <code>isPrime</code> function -- but using just primes is better, produced e.g. by [[Sieve of Eratosthenes#Haskell|Sieve of Eratosthenes]], or <code>noDivsBy</code> itself can be used to define <code>primeNums</code> as shown above, because it stops when the square root is reached (so there's no infinite recursion, no "vicious circle").
 
A less efficient, more basic variant:
<langsyntaxhighlight lang="haskell">isPrime n = n > 1 && []==[i | i <- [2..n-1], rem n i == 0]</langsyntaxhighlight>
 
The following is an attempt at improving it, resulting in absolutely worst performing prime testing code I've ever seen, ever. A curious oddity.
<langsyntaxhighlight lang="haskell">isPrime n = n > 1 && []==[i | i <- [2..n-1], isPrime i && rem n i == 0]</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest"> DO n = 1, 1E6
Euler = n^2 + n + 41
IF( Prime(Euler) == 0 ) WRITE(Messagebox) Euler, ' is NOT prime for n =', n
Line 1,680 ⟶ 2,852:
Prime = 1
ENDIF
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Procedure shown without a main program.
<langsyntaxhighlight Iconlang="icon">procedure isprime(n) #: return n if prime (using trial division) or fail
if not n = integer(n) | n < 2 then fail # ensure n is an integer greater than 1
every if 0 = (n % (2 to sqrt(n))) then fail
return n
end</langsyntaxhighlight>
 
=={{header|J}}==
{{eff note|J|1&p:}}
<langsyntaxhighlight lang="j">isprime=: 3 : 'if. 3>:y do. 1<y else. 0 *./@:< y|~2+i.<.%:y end.'</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public static boolean prime(long a){
if(a == 2){
return true;
Line 1,706 ⟶ 2,878:
}
return true;
}</langsyntaxhighlight>
===By Regular Expression===
<langsyntaxhighlight lang="java">public static boolean prime(int n) {
return !new String(new char[n]).matches(".?|(..+?)\\1+");
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function isPrime(n) {
if (n == 2 || n == 3 || n == 5 || n == 7) {
return true;
Line 1,725 ⟶ 2,897:
return true;
}
}</langsyntaxhighlight>
 
=={{header|Joy}}==
<syntaxhighlight lang joy>DEFINE prime ==
From [http://www.latrobe.edu.au/phimvt/joy/jp-imper.html here]
2 [[dup * >] nullary [rem 0 >] dip and]
<lang joy>DEFINE prime ==
[succ] while dup * <.</syntaxhighlight>
2
[ [dup * >] nullary [rem 0 >] dip and ]
[ succ ]
while
dup * < .</lang>
 
=={{header|jq}}==
Line 1,764 ⟶ 2,932:
=={{header|Julia}}==
Julia already has an <tt>isprime</tt> function, so this function has the verbose name <tt>isprime_trialdivision</tt> to avoid overriding the built-in function. Note this function relies on the fact that Julia skips <tt>for</tt>-loops having invalid ranges. Otherwise the function would have to include additional logic to check the odd numbers less than 9.
<langsyntaxhighlight Julialang="julia">function isprime_trialdivision{T<:Integer}(n::T)
1 < n || return false
n != 2 || return true
Line 1,781 ⟶ 2,949:
else
println("The function does not accurately calculate primes.")
end</langsyntaxhighlight>
{{out}}
The primes <= 100 are:
Line 1,787 ⟶ 2,955:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> isprime:{(x>1)&&/x!'2_!1+_sqrt x}
&isprime'!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</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
fun isPrime(n: Int): Boolean {
if (n < 2) return false
Line 1,803 ⟶ 2,971:
// test by printing all primes below 100 say
(2..99).filter { isPrime(it) }.forEach { print("$it ") }
}</langsyntaxhighlight>
{{out}}
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
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
1) the simplest
 
{def isprime1
{def isprime1.loop
{lambda {:n :m :i}
{if {> :i :m}
then true
else {if {= {% :n :i} 0}
then false
else {isprime1.loop :n :m {+ :i 1}} }
}}}
{lambda {:n}
{isprime1.loop :n {sqrt :n} 2}
}}
-> isprime1
 
2) slightly improved
 
{def isprime2
{def isprime2.loop
{lambda {:n :m :i}
{if {> :i :m}
then true
else {if {= {% :n :i} 0}
then false
else {isprime2.loop :n :m {+ :i 2}}
}}}}
{lambda {:n}
{if {or {= :n 2} {= :n 3} {= :n 5} {= :n 7}}
then true
else {if {or {< : n 2} {= {% :n 2} 0}}
then false
else {isprime2.loop :n {sqrt :n} 3}
}}}}
-> isprime2
 
3) testing
 
{isprime1 1299709} -> stackoverflow on my iPad Pro
{isprime2 1299709} -> true
 
{def primesTo
{lambda {:f :n}
{S.replace \s by space in
{S.map {{lambda {:f :i} {if {:f :i} then :i else}} :f}
{S.serie 2 :n}}} }}
-> primesTo
 
{primesTo isprime1 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 in 25ms
{primesTo isprime2 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 in 20ms
 
{primesTo isprime1 1000000} in about 30000ms
{primesTo isprime2 1000000} in about 15000ms
 
</syntaxhighlight>
 
=={{header|langur}}==
=== Functional ===
{{trans|Raku}}
following the Raku example, which states, "Integer $i is prime if it is greater than one and is divisible by none of 2, 3, up to the square root of $i" (plus an adjustment for the prime number 2)
 
Below, we use an implied parameter (.i) on the .isPrime function.
 
<syntaxhighlight lang="langur">val .isPrime = fn(.i) {
.i == 2 or .i > 2 and
not any fn(.x) { .i div .x }, pseries 2 .. .i ^/ 2
}
 
writeln filter .isPrime, series 100</syntaxhighlight>
 
=== Recursive ===
{{trans|Go}}
<syntaxhighlight lang="langur">val .isPrime = fn(.i) {
{{works with|langur|0.8.1}}
<lang langur>val .isPrime = f(.i) {
val .n = abs(.i)
if .n <= 2: return .n == 2
 
val .chkdiv = ffn(.n, .i) {
if .i x* .i <= .n {
return .n ndiv .i and self(.n, .i+2)
}
Line 1,825 ⟶ 3,065:
}
 
writeln wherefilter .isPrime, series 100</langsyntaxhighlight>
 
=== Functional ===
{{trans|Raku}}
following the Raku example, which states, "Integer $i is prime if it is greater than one and is divisible by none of 2, 3, up to the square root of $i" (plus an adjustment for the prime number 2)
{{works with|langur|0.8.1}}
<lang langur>val .isPrime = f .i == 2 or .i > 2 and not any f(.x) .i div .x, pseries 2 to .i ^/ 2
 
writeln where .isPrime, series 100</lang>
 
{{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|Liberty BASIC}}==
<lang lb>print "Rosetta Code - Primality by trial division"
print
[start]
input "Enter an integer: "; x
if x=0 then print "Program complete.": end
if isPrime(x) then print x; " is prime" else print x; " is not prime"
goto [start]
 
function isPrime(p)
p=int(abs(p))
if p=2 or then isPrime=1: exit function 'prime
if p=0 or p=1 or (p mod 2)=0 then exit function 'not prime
for i=3 to sqr(p) step 2
if (p mod i)=0 then exit function 'not prime
next i
isPrime=1
end function</lang>
{{out}}
<pre>Rosetta Code - Primality by trial division
 
Enter an integer: 1
1 is not prime
Enter an integer: 2
2 is prime
Enter an integer:
Program complete.</pre>
 
=={{header|Lingo}}==
<langsyntaxhighlight Lingolang="lingo">on isPrime (n)
if n<=1 or (n>2 and n mod 2=0) then return FALSE
sq = sqrt(n)
Line 1,874 ⟶ 3,078:
end repeat
return TRUE
end</langsyntaxhighlight>
<langsyntaxhighlight Lingolang="lingo">primes = []
repeat with i = 0 to 100
if isPrime(i) then primes.add(i)
end repeat
put primes</langsyntaxhighlight>
{{out}}
-- [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]
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to prime? :n
if :n < 2 [output "false]
if :n = 2 [output "true]
Line 1,890 ⟶ 3,094:
for [i 3 [sqrt :n] 2] [if equal? 0 modulo :n :i [output "false]]
output "true
end</langsyntaxhighlight>
 
=={{header|LSE64}}==
<langsyntaxhighlight LSE64lang="lse64">over : 2 pick
2dup : over over
even? : 1 & 0 =
Line 1,907 ⟶ 3,111:
prime? : dup even? then drop false
prime? : dup 2 = then drop true
prime? : dup 2 < then drop false</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function IsPrime( n )
if n <= 1 or ( n ~= 2 and n % 2 == 0 ) then
return false
Line 1,922 ⟶ 3,126:
 
return true
end</langsyntaxhighlight>
Type of number Decimal.
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Primality_by_trial_division {
Inventory Known1=2@, 3@
Inventory Known1=2@, 3@
IsPrime=lambda Known1 (x as decimal) -> {
IsPrime=lambda Known1 (x as decimal) -> {
=0=1
=false
if exist(Known1, x) then =1=1 : exit
if exist(Known1, x) then =true : exit
if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x : =1=1
if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x : =true
Break}
Break}
if frac(x/2) else exit
if frac(x/32) else exit
if frac(x/3) else exit
x1=sqrt(x):d = 5@
x1=sqrt(x):d = 5@
{if frac(x/d ) else exit
do
d += 2: if d>x1 then Append Known1, x : =1=1 : exit
if frac(x/d) else exit
d += 42: if d<= >x1 elsethen Append Known1, x : =true =1=1: exit
if frac(x/d) else exit
loop}
d += 4: if d<= x1 else Append Known1, x : =true: exit
}
always
}
i=2
While Len(Known1)<20 {
i=2
dummy=Isprime(i)
While Len(Known1)<20
i++
dummy=Isprime(i) }
i++
Print "first ";len(known1);" primes"
End While
Print Known1
Print "Fromfirst 110 to";len(known1);" 130primes"
Print Known1
count=0
Print "From For i=110 to 130 {"
count=0
If isPrime(i) Then Print i, : count++
For i=110 to 130
}
If isPrime(i) Then Print i, : count++
Print
Next
Print "Found ";count;" primes"
Print
</lang>
Print "Found ";count;" primes"
}
Primality_by_trial_division
</syntaxhighlight>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`testnext',
`ifelse(eval($2*$2>$1),1,
1,
Line 1,974 ⟶ 3,182:
 
isprime(9)
isprime(11)</langsyntaxhighlight>
{{out}}
0
1
 
=={{header|MAD}}==
<syntaxhighlight lang="MAD"> NORMAL MODE IS INTEGER
 
INTERNAL FUNCTION(N)
ENTRY TO PRIME.
WHENEVER N.L.2, FUNCTION RETURN 0B
WHENEVER N.E.N/2*2, FUNCTION RETURN N.E.2
THROUGH TRIAL, FOR FAC=3, 2, FAC*FAC.G.N
TRIAL WHENEVER N.E.N/FAC*FAC, FUNCTION RETURN 0B
FUNCTION RETURN 1B
END OF FUNCTION
 
PRINT COMMENT $ PRIMES UNDER 100 $
THROUGH CAND, FOR C=0, 1, C.G.100
CAND WHENEVER PRIME.(C), PRINT FORMAT PR,C
VECTOR VALUES PR = $ I3*$
 
END OF PROGRAM</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|Maple}}==
This could be coded in myriad ways; here is one.
<langsyntaxhighlight Maplelang="maple">TrialDivision := proc( n :: integer )
if n <= 1 then
false
Line 1,996 ⟶ 3,250:
true
end if
end proc:</langsyntaxhighlight>
Using this to pick off the primes up to 30, we get:
<langsyntaxhighlight Maplelang="maple">> select( TrialDivision, [seq]( 1 .. 30 ) );
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]</langsyntaxhighlight>
Here is a way to check that TrialDivision above agrees with Maple's built-in primality test (isprime).
<langsyntaxhighlight Maplelang="maple">> N := 10000: evalb( select( TrialDivision, [seq]( 1 .. N ) ) = select( isprime, [seq]( 1 .. N ) ) );
true</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">IsPrime[n_Integer] := Block[{},
If[n <= 1, Return[False]];
If[n == 2, Return[True]]; If[Mod[n, 2] == 0, Return[False]];
For[k = 3, k <= Sqrt[n], k += 2, If[Mod[n, k] == 0, Return[False]]];
Return[True]]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function isPrime = primalityByTrialDivision(n)
 
if n == 2
Line 2,030 ⟶ 3,284:
isPrime = all(mod(n, (3:round(sqrt(n))) ));
end</langsyntaxhighlight>
{{out|Sample output}}
<langsyntaxhighlight MATLABlang="matlab">>> arrayfun(@primalityByTrialDivision,(1:14))
 
ans =
 
0 1 1 0 1 0 1 0 0 0 1 0 1 0</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight Maximalang="maxima">isprme(n):= catch(
for k: 2 thru sqrt(n) do if mod(n, k)=0 then throw(false),
true);
 
map(isprme, [2, 3, 4, 65, 100, 181, 901]);
/* [true, true, false, false, false, true, false] */</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">(
:n 3 :i n sqrt :m true :p
(i m <=) (
Line 2,062 ⟶ 3,316:
((true) (_prime?))
) case
) :prime?</langsyntaxhighlight>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (show (filter prime [1..100])),
Stdout "\n"]
 
prime :: num->bool
prime n = n=2 \/ n=3, if n<=4
= False, if n mod 2=0
= #[d | d<-[3, 5..sqrt n]; n mod d=0]=0, 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|МК-61/52}}==
<syntaxhighlight lang="text">П0 1 - x#0 34 2 - /-/ x<0 32
ИП0 2 / {x} x#0 34
3 П4 ИП0 ИП4 / {x} x#0 34 КИП4 КИП4
ИП0 КвКор ИП4 - x<0 16 1 С/П 0 С/П</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE TrialDivision;
FROM InOut IMPORT WriteCard, WriteLn;
 
CONST
Max = 100;
VAR
i: CARDINAL;
 
PROCEDURE prime(n: CARDINAL): BOOLEAN;
VAR
factor: CARDINAL;
BEGIN
IF n <= 4 THEN
RETURN (n = 2) OR (n = 3)
ELSIF n MOD 2 = 0 THEN
RETURN FALSE
ELSE
factor := 3;
WHILE factor * factor <= n DO
IF n MOD factor = 0 THEN
RETURN FALSE
END;
INC(factor, 2)
END
END;
RETURN TRUE
END prime;
 
BEGIN
FOR i := 0 TO Max DO
IF prime(i) THEN
WriteCard(i,3);
WriteLn
END
END
END TrialDivision.</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|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">ISPRIME(N)
QUIT:(N=2) 1
NEW I,R
Line 2,077 ⟶ 3,407:
IF R FOR I=3:2:(N**.5) SET R=N#I Q:'R
KILL I
QUIT R</langsyntaxhighlight>
Usage (0 is false, nonzero is true):
<pre>USER>W $$ISPRIME^ROSETTA(2)
Line 2,091 ⟶ 3,421:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
Line 2,156 ⟶ 3,486:
 
method isFalse public static returns boolean
return \isTrue</langsyntaxhighlight>
{{out}}
<pre>$ java -cp . RCPrimality
Line 2,190 ⟶ 3,520:
===[[#REXX|Rexx]] version reimplemented in [[NetRexx]]===
{{trans|REXX}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
Line 2,221 ⟶ 3,551:
end
 
return 1 /*I'm exhausted, it's prime!*/</langsyntaxhighlight>
 
=={{header|newLISP}}==
Short-circuit evaluation ensures that the many Boolean expressions are calculated in the right order so as not to waste time.
<syntaxhighlight lang="newlisp">; Here are some simpler functions to help us:
 
(define (divisible? larger-number smaller-number)
(zero? (% larger-number smaller-number)))
 
(define (int-root number)
(floor (sqrt number)))
 
(define (even-prime? number)
(= number 2))
 
; Trial division for odd numbers
 
(define (find-odd-factor? odd-number)
(catch
(for (possible-factor 3 (int-root odd-number) 2)
(if (divisible? odd-number possible-factor)
(throw true)))))
 
(define (odd-prime? number)
(and
(odd? number)
(or
(= number 3)
(and
(> number 3)
(not (find-odd-factor? number))))))
 
; Now for the final overall Boolean function.
 
(define (is-prime? possible-prime)
(or
(even-prime? possible-prime)
(odd-prime? possible-prime)))
 
; Let's use this to actually find some prime numbers.
 
(println (filter is-prime? (sequence 1 100)))
(exit)</syntaxhighlight>
 
{{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)
 
=={{header|Nim}}==
Here are three ways to test primality using trial division.
<lang nim>import sequtils, math
<syntaxhighlight lang="nim">import sequtils, math
 
proc prime(a: int): bool =
Line 2,233 ⟶ 3,609:
return false
return true
 
template any(sequence, operation: expr): expr =
var result {.gensym.}: bool = false
for i in 0 .. <sequence.len:
let it {.inject.} = sequence[i]
result = operation
if result:
break
result
 
proc prime2(a: int): bool =
Line 2,252 ⟶ 3,619:
 
for i in 2..30:
echo i, " ", prime(i)</langsyntaxhighlight>
 
{{out}}
<pre>2 true
3 true
4 false
5 true
6 false
7 true
8 false
9 false
10 false
11 true
12 false
13 true
14 false
15 false
16 false
17 true
18 false
19 true
20 false
21 false
22 false
23 true
24 false
25 false
26 false
27 false
28 false
29 true
30 false</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">function : IsPrime(n : Int) ~ Bool {
if(n <= 1) {
return false;
Line 2,267 ⟶ 3,665:
return true;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let is_prime n =
iflet nrec =test 2x then true=
else if nx <* 2x > n || n mod x <> 0 && n mod (x + 2) =<> 0 then&& test (x + false6)
elsein
if n let< rec loop k =5
then n lor 1 = 3
if k * k > n then true
else n land 1 else<> if0 && n mod k3 =<> 0 then&& test false5</syntaxhighlight>
else loop (k+2)
in loop 3</lang>
 
=={{header|Octave}}==
This function works on vectors and matrix.
<langsyntaxhighlight lang="octave">function b = isthisprime(n)
for r = 1:rows(n)
for c = 1:columns(n)
Line 2,306 ⟶ 3,702:
p = [1:100];
pv = isthisprime(p);
disp(p( pv ));</langsyntaxhighlight>
 
=={{header|Oforth}}==
<langsyntaxhighlight Oforthlang="oforth">Integer method: isPrime
| i |
self 1 <= ifTrue: [ false return ]
Line 2,315 ⟶ 3,711:
self isEven ifTrue: [ false return ]
3 self sqrt asInteger for: i [ self i mod ifzero: [ false return ] ]
true ;</langsyntaxhighlight>
{{out}}
<pre>#isPrime 1000 seq filter println
Line 2,330 ⟶ 3,726:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (prime? number)
(define max (sqrt number))
Line 2,342 ⟶ 3,738:
(> (modulo number 2) 0)
(loop 3))))
</syntaxhighlight>
</lang>
Testing:
<langsyntaxhighlight lang="scheme">
; first prime numbers less than 100
(for-each (lambda (n)
Line 2,364 ⟶ 3,760:
12345676543211234567654321123456765432112345676543211234567654321123456765432112345676543211234567654321
))
</syntaxhighlight>
</lang>
{{out}}
<pre> 1 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,376 ⟶ 3,772:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz"> fun {Prime N}
local IPrime in
fun {IPrime N Acc}
Line 2,387 ⟶ 3,783:
else {IPrime N 2} end
end
end</langsyntaxhighlight>
 
=={{header|Panda}}==
In Panda you write a boolean function by making it filter, either returning it's input or nothing.
<langsyntaxhighlight lang="panda">fun prime(p) type integer->integer
p.gt(1) where q=p.sqrt NO(p.mod(2..q)==0)
 
1..100.prime</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">trial(n)={
if(n < 4, return(n > 1)); /* Handle negatives */
forprime(p=2,sqrtsqrtint(n),
if(n%p == 0, return(0))
);
1
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{trans|BASICQuickBASIC}}
<langsyntaxhighlight Pascallang="pascal">program primes;
 
function prime(n: integer): boolean;
Line 2,435 ⟶ 3,831:
if (prime(n)) then
write(n, ' ');
end.</langsyntaxhighlight>
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
===improved using number wheel===
{{libheader|primTrial}}{{works with|Free Pascal}}
<langsyntaxhighlight lang="pascal">program TestTrialDiv;
{$IFDEF FPC}
{$MODE DELPHI}{$Smartlink ON}
Line 2,453 ⟶ 3,849:
write(actPrime,' ');
until nextPrime > 50;
end.</langsyntaxhighlight>
;Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Line 2,459 ⟶ 3,855:
=={{header|Perl}}==
A simple idiomatic solution:
<langsyntaxhighlight lang="perl">sub prime { my $n = shift || $_;
$n % $_ or return for 2 .. sqrt $n;
$n > 1
}
 
print join(', ' => grep prime, 1..100), "\n";</langsyntaxhighlight>
 
===Excluding multiples of 2 and 3===
One of many ways of writing trial division using a mod-6 wheel. Almost 2x faster than the simple method shown earlier.
<langsyntaxhighlight lang="perl">sub isprime {
my $n = shift;
return ($n >= 2) if $n < 4;
Line 2,480 ⟶ 3,876:
my $s = 0;
$s += !!isprime($_) for 1..100000;
print "Pi(100,000) = $s\n";</langsyntaxhighlight>
===By Regular Expression===
Line 2,486 ⟶ 3,882:
 
While this is extremely clever and often used for [[wp:Code golf|Code golf]], it should never be used for real work (it is extremely slow and uses lots of memory).
<langsyntaxhighlight lang="perl">sub isprime {
('1' x shift) !~ /^1?$|^(11+?)\1+$/
}
print join(', ', grep(isprime($_), 0..39)), "\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function is_prime(integer n)
<span style="color: #008080;">function</span> <span style="color: #000000;">is_prime_by_trial_division</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
if n<2 then return 0 end if
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if n=2 then return 1 end if
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if remainder(n,2)=0 then return 0 end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
for i=3 to floor(sqrt(n)) by 2 do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
if remainder(n,i)=0 then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
return 0
<span style="color: #008080;">return</span> <span style="color: #000000;">0</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return 1
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
end function</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">32</span><span style="color: #0000FF;">),</span><span style="color: #000000;">is_prime_by_trial_division</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{2,3,5,7,11,13,17,19,23,29,31}
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
function prime($a) {
if (($a % 2 == 0 && $a != 2) || $a < 2)
Line 2,519 ⟶ 3,922:
if (prime($x)) echo "$x\n";
 
?></langsyntaxhighlight>
===By Regular Expression===
<langsyntaxhighlight lang="php"><?php
function prime($a) {
return !preg_match('/^1?$|^(11+?)\1+$/', str_repeat('1', $a));
}
?></langsyntaxhighlight>
 
=={{header|Picat}}==
Here are four different versions.
===Iterative===
<syntaxhighlight lang="picat">is_prime1(N) =>
if N == 2 then
true
elseif N <= 1 ; N mod 2 == 0 then
false
else
foreach(I in 3..2..ceiling(sqrt(N)))
N mod I > 0
end
end.</syntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="picat">is_prime2(N) =>
(N == 2 ; is_prime2b(N,3)).
 
is_prime2b(N,_Div), N <= 1 => false.
is_prime2b(2,_Div) => true.
is_prime2b(N,_Div), N mod 2 == 0 => false.
is_prime2b(N,Div), Div > ceiling(sqrt(N)) => true.
is_prime2b(N,Div), Div > 2 =>
(N mod Div == 0 ->
false
;
is_prime2b(N,Div+2)
).</syntaxhighlight>
 
===Functional===
<syntaxhighlight lang="picat">is_prime3(2) => true.
is_prime3(3) => true.
is_prime3(P) => P > 3, P mod 2 =\= 0, not has_factor3(P,3).
 
has_factor3(N,L), N mod L == 0 => true.
has_factor3(N,L) => L * L < N, L2 = L + 2, has_factor3(N,L2).</syntaxhighlight>
 
===Generator approach===
{{trans|Prolog}}
<code>prime2(N)</code> can be used to generate primes until memory is exhausted.
 
Difference from Prolog implementation: Picat does not support <code>between/3</code> with
"inf" as upper bound, so a high number (here 2**156+1) must be used.
<syntaxhighlight lang="picat">prime2(2).
prime2(N) :-
between(3, 2**156+1, N),
N mod 2 = 1, % odd
M is floor(sqrt(N+1)), % round-off paranoia
Max is (M-1) // 2, % integer division
foreach(I in 1..Max) N mod (2*I+1) > 0 end.</syntaxhighlight>
 
===Test===
<syntaxhighlight lang="picat">go =>
println([I : I in 1..100, is_prime1(I)]),
nl,
foreach(P in 1..6)
Primes = [ I : I in 1..10**P, is_prime1(I)],
println([10**P,Primes.len])
end,
nl.</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]
 
[10,4]
[100,25]
[1000,168]
[10000,1229]
[100000,9592]
[1000000,78498]</pre>
 
===Benchmark===
Times for calculating the number of primes below 10, 100,1_000,10_000, 100_000, and 1_000_000 respectively.
 
* imperative: <code>is_prime1/1</code> (0.971)
* recursive: <code>is_prime2/1</code> (3.258s)
* functional: <code>is_prime3/1</code> (0.938s)
* test/generate <code>prime2/1</code> (2.129s)
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de prime? (N)
(or
(= N 2)
Line 2,537 ⟶ 4,020:
(for (D 3 T (+ D 2))
(T (> D S) T)
(T (=0 (% N D)) NIL) ) ) ) ) )</langsyntaxhighlight>
 
=={{header|PL/0}}==
The program waits for a number. Then it displays 1 if the number is prime, 0 otherwise.
<syntaxhighlight lang="pascal">
var p, isprime;
 
procedure checkprimality;
var i, isichecked;
begin
isprime := 0;
if p = 2 then isprime := 1;
if p >= 3 then
begin
i := 2; isichecked := 0;
while isichecked = 0 do
begin
if (p / i) * i = p then isichecked := 1;
if isichecked <> 1 then
if i * i >= p then
begin
isprime := 1; isichecked := 1
end;
i := i + 1
end
end
end;
 
begin
? p;
call checkprimality;
! isprime
end.
</syntaxhighlight>
4 runs:
{{in}}
<pre>1</pre>
{{out}}
<pre> 0</pre>
{{in}}
<pre>25</pre>
{{out}}
<pre> 0</pre>
{{in}}
<pre>43</pre>
{{out}}
<pre> 1</pre>
{{in}}
<pre>101</pre>
{{out}}
<pre> 1</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PL/Ilang="pli">is_prime: procedure (n) returns (bit(1));
declare n fixed (15);
declare i fixed (10);
Line 2,552 ⟶ 4,085:
end;
return ('1'b);
end is_prime;</langsyntaxhighlight>
 
=={{header|PL/M}}==
This can be compiled with the original 8080 PL/M compiler and run under CP/M or an emulator or clone.
<br>Note that all integers in 8080 PL/M are unsigned.
<syntaxhighlight lang="pli">100H: /* TEST FOR PRIMALITY BY TRIAL DIVISION */
 
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, 0AH, '$' ) ); END;
PR$NUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
N$STR( W := LAST( N$STR ) ) = '$';
N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
/* INTEGER SUARE ROOT: BASED ON THE ONE IN THE PL/M FOR FROBENIUS NUMBERS */
SQRT: PROCEDURE( N )ADDRESS;
DECLARE ( N, X0, X1 ) ADDRESS;
IF N <= 3 THEN DO;
IF N = 0 THEN X0 = 0; ELSE X0 = 1;
END;
ELSE DO;
X0 = SHR( N, 1 );
DO WHILE( ( X1 := SHR( X0 + ( N / X0 ), 1 ) ) < X0 );
X0 = X1;
END;
END;
RETURN X0;
END SQRT;
 
IS$PRIME: PROCEDURE( N )BYTE; /* RETURNS TRUE IF N IS PRIME, FALSE IF NOT */
DECLARE N ADDRESS;
IF N < 2 THEN RETURN FALSE;
ELSE IF ( N AND 1 ) = 0 THEN RETURN N = 2;
ELSE DO;
/* ODD NUMBER > 2 */
DECLARE I ADDRESS;
DO I = 3 TO SQRT( N ) BY 2;
IF N MOD I = 0 THEN RETURN FALSE;
END;
RETURN TRUE;
END;
END IS$PRIME;
 
/* TEST THE IS$PRIME PROCEDURE */
DECLARE I ADDRESS;
DO I = 0 TO 100;
IF IS$PRIME( I ) THEN DO;
CALL PR$CHAR( ' ' );
CALL PR$NUMBER( I );
END;
END;
CALL PR$NL;
 
EOF</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|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function isPrime ($n) {
if ($n -eq 1) {$false}
Line 2,565 ⟶ 4,164:
}
}
1..15 | foreach{"isPrime $_ : $(isPrime $_)"}</langsyntaxhighlight>
<b>Output:</b>
<pre>isPrime 1 : False
Line 2,585 ⟶ 4,184:
=={{header|Prolog}}==
The following predicate showcases Prolog's support for writing predicates suitable for both testing and generating. In this case, assuming the Prolog implemenation supports indefinitely large integers, prime(N) can be used to generate primes until memory is exhausted.
<langsyntaxhighlight Prologlang="prolog">prime(2).
prime(N) :-
between(3, inf, N),
Line 2,591 ⟶ 4,190:
M is floor(sqrt(N+1)), % round-off paranoia
Max is (M-1) // 2, % integer division
forall( between(1, Max, I), N mod (2*I+1) > 0 ).</langsyntaxhighlight>
Example using SWI-Prolog:
<pre>?- time( (bagof( P, (prime(P), ((P > 100000, !, fail); true)), Bag),
Line 2,608 ⟶ 4,207:
 
?-</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>Procedure.i IsPrime(n)
Protected k
 
If n = 2
ProcedureReturn #True
EndIf
 
If n <= 1 Or n % 2 = 0
ProcedureReturn #False
EndIf
For k = 3 To Int(Sqr(n)) Step 2
If n % k = 0
ProcedureReturn #False
EndIf
Next
 
ProcedureReturn #True
EndProcedure</lang>
 
=={{header|Python}}==
The simplest primality test, using trial division:
{{works with|Python|2.5}}
<langsyntaxhighlight lang="python">def prime(a):
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))</langsyntaxhighlight>
Another test. Exclude even numbers first:
<langsyntaxhighlight lang="python">def prime2(a):
if a == 2: return True
if a < 2 or a % 2 == 0: return False
return not any(a % x == 0 for x in xrange(3, int(a**0.5) + 1, 2))</langsyntaxhighlight>
Yet another test. Exclude multiples of 2 and 3, see http://www.devx.com/vb2themax/Tip/19051:
{{works with|Python|2.4}}
<langsyntaxhighlight lang="python">def prime3(a):
if a < 2: return False
if a == 2 or a == 3: return True # manually test 2 and 3
Line 2,654 ⟶ 4,232:
i = 6 - i # this modifies 2 into 4 and viceversa
 
return True</langsyntaxhighlight>
===By Regular Expression===
Regular expression by "Abigail".<br>
(An explanation is given in "[http://paddy3118.blogspot.com/2009/08/story-of-regexp-and-primes.html The Story of the Regexp and the Primes]").
<langsyntaxhighlight lang="python">>>> import re
>>> def isprime(n):
return not re.match(r'^1?$|^(11+?)\1+$', '1' * n)
Line 2,664 ⟶ 4,242:
>>> # A quick test
>>> [i for i in range(40) if isprime(i)]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]</langsyntaxhighlight>
 
=={{header|Qi}}==
<langsyntaxhighlight Qilang="qi">(define prime?-0
K N -> true where (> (* K K) N)
K N -> false where (= 0 (MOD N K))
Line 2,676 ⟶ 4,254:
2 -> true
N -> false where (= 0 (MOD N 2))
N -> (prime?-0 3 N))</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<code>sqrt+</code> is defined at [[Isqrt (integer square root) of X#Quackery]].
 
<syntaxhighlight lang="quackery"> [ dup 4 < iff [ 1 > ] done
dup 1 & not iff [ drop false ] done
true swap dup sqrt+
0 = iff [ 2drop not ] done
1 >> times
[ dup i^ 1 << 3 + mod 0 = if
[ dip not conclude ] ]
drop ] is isprime ( n --> b )
</syntaxhighlight>
 
=={{header|R}}==
<syntaxhighlight lang="rsplus">is.prime <- function(n) n == 2 || n > 2 && n %% 2 == 1 && (n < 9 || all(n %% seq(3, floor(sqrt(n)), 2) > 0))
<lang R>isPrime <- function(n) {
if (n == 2) return(TRUE)
if ( (n <= 1) || ( n %% 2 == 0 ) ) return(FALSE)
for( i in 3:sqrt(n) ) {
if ( n %% i == 0 ) return(FALSE)
}
TRUE
}</lang>
 
<lang R>printwhich(lapplysapply(1:100, isPrimeis.prime))</lang>
# [1] 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</syntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (prime? number)
Line 2,698 ⟶ 4,284:
((even? number) (= 2 number))
(else (for/and ((i (in-range 3 (ceiling (sqrt number)))))
(not (zero? (remainder number i)))))))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
Here we use a "none" junction which will autothread through the <tt>%%</tt> "is divisible by" operator to assert that <tt>$i</tt> is not divisible by 2 or any of the numbers up to its square root. Read it just as you would English: "Integer <tt>$i</tt> is prime if it is greater than one and is divisible by none of 2, 3, up to the square root of <tt>$i</tt>."
<syntaxhighlight lang="raku" perl6line>sub prime (Int $i --> Bool) {
$i > 1 and so $i %% none 2..$i.sqrt;
}</langsyntaxhighlight>
 
This can easily be improved in two ways. First, we generate the primes so we only divide by those, instead of all odd numbers. Second, we memoize the result using the <tt>//=</tt> idiom of Perl, which does the right-hand calculation and assigns it only if the left side is undefined. We avoid recalculating the square root each time. Note the mutual recursion that depends on the implicit laziness of list evaluation:
<syntaxhighlight lang="raku" perl6line>my @primes = 2, 3, 5, -> $p { ($p+2, $p+4 ... &prime)[*-1] } ... *;
my @isprime = False,False; # 0 and 1 are not prime by definition
sub prime($i) {
Line 2,715 ⟶ 4,301:
}
 
say "$_ is{ "n't" x !prime($_) } prime." for 1 .. 100;</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">prime?: func [n] [
case [
n = 2 [ true ]
Line 2,729 ⟶ 4,315:
]
]
]</langsyntaxhighlight>
 
<langsyntaxhighlight REBOLlang="rebol">repeat i 100 [ print [i prime? i]]</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,744 ⟶ 4,330:
<br>function slowed up the function &nbsp; (for all three REXX versions), &nbsp; however, for larger numbers of &nbsp; '''N''', &nbsp; it would
<br>be faster.
<langsyntaxhighlight lang="rexx">/*REXX program tests for primality by using (kinda smartish) trial division. */
parse arg n .; if n=='' then n=10000 /*let the user choose the upper limit. */
tell=(n>0); n=abs(n) /*display the primes only if N > 0. */
Line 2,764 ⟶ 4,350:
end /*k*/ /*divide up through the √ x */
/*Note: // is ÷ remainder.*/
return 1 /*done dividing, it's prime. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input of: &nbsp; <tt> 100 </tt>}}
<pre>
Line 2,798 ⟶ 4,384:
This version separates multiple-clause &nbsp; '''if''' &nbsp; statements, and also tests for low primes,
<br>making it about 8% faster.
<langsyntaxhighlight lang="rexx">/*REXX program tests for primality by using (kinda smartish) trial division. */
parse arg n .; if n=='' then n=10000 /*let the user choose the upper limit. */
tell=(n>0); n=abs(n) /*display the primes only if N > 0. */
Line 2,819 ⟶ 4,405:
if x//(k+2)==0 then return 0 /* ··· and the next umpty one. */
end /*k*/ /*Note: REXX // is ÷ remainder.*/
return 1 /*did all divisions, it's prime. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the first version when the same input is used.}}
 
Line 2,826 ⟶ 4,412:
<br>also an optimized version of the testing of low primes is used, making it about 22% faster.
<br><br>Note that the &nbsp; '''do ... until ...''' &nbsp; was changed to &nbsp; '''do ... while ...'''.
<langsyntaxhighlight lang="rexx">/*REXX program tests for primality by using (kinda smartish) trial division. */
parse arg n .; if n=='' then n=10000 /*let the user choose the upper limit. */
tell=(n>0); n=abs(n) /*display the primes only if N > 0. */
Line 2,874 ⟶ 4,460:
if x//(k+2)==0 then return 0 /* ··· and the next also. ___ */
end /*k*/ /*divide up through the √ x */
return 1 /*after all that, ··· it's a prime. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the first version when the same input is used.}}<br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">give n
flag = isPrime(n)
if flag = 1 see n + " is a prime number"
Line 2,889 ⟶ 4,475:
if (num % i = 0) return 0 ok
next
return 1</langsyntaxhighlight>
 
=={{header|RPL}}==
{{trans|Python}}
This version use binary integers
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ / LAST ROT * - #0 == ≫ '<span style="color:blue">BDIV?</span>' STO
'''IF''' DUP #3 ≤ '''THEN''' #2 / B→R
'''ELSE'''
'''IF''' DUP #2 <span style="color:blue">BDIV?</span> OVER #3 '''BDIV?''' OR
'''THEN''' DROP 0
'''ELSE'''
DUP B→R √ R→B → a maxd
≪ a #2 #5 1 SF
'''WHILE''' 1 FS? OVER maxd ≤ AND '''REPEAT'''
'''IF''' a OVER <span style="color:blue">BDIV?</span> '''THEN''' 1 CF '''END'''
OVER + #6 ROT - SWAP '''END'''
SWAP DROP <span style="color:blue">BDIV?</span> NOT
'''END'''
'''END'''
≫ '<span style="color:blue">BPRIM?</span>' STO
|
<span style="color:blue">BDIV?</span> ''( #a #b -- boolean )''
<span style="color:blue">BPRIM?</span> ''( #a -- boolean )''
return 1 if a is 2 or 3
if 2 or 3 divides a
return 0
else
store a and root(a)
initialize stack with a i d and set flag 1 to control loop exit
while d <= root(a)
prepare loop exit if d divides a
i = 6 - i which modifies 2 into 4 and viceversa
empty stack and return result
|}
'''Floating point version'''
 
Faster but limited to 1E12.
≪ '''IF''' DUP 5 ≤ '''THEN''' { 2 3 5 } SWAP POS
'''ELSE'''
'''IF''' DUP 2 MOD NOT '''THEN''' 2
'''ELSE'''
DUP √ CEIL → lim
≪ 3 '''WHILE''' DUP2 MOD OVER lim ≤ AND '''REPEAT''' 2 + '''END'''
'''END''' MOD
'''END''' SIGN
≫ '<span style="color:blue">PRIM?</span>' STO
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def prime(a)
if a == 2
true
Line 2,902 ⟶ 4,549:
end
end
p (1..50).select{|i| prime(i)}</langsyntaxhighlight>
 
The '''prime''' package in the stdlib for Ruby contains this compact <code>Prime#prime?</code> method:
<langsyntaxhighlight lang="ruby">require "prime"
def prime?(value, generator = Prime::Generator23.new)
return false if value < 2
Line 2,914 ⟶ 4,561:
end
end
p (1..50).select{|i| prime?(i)}</langsyntaxhighlight>
 
Without any fancy stuff:
<langsyntaxhighlight lang="ruby">def primes(limit)
(enclose = lambda { |primes|
primes.last.succ.upto(limit) do |trial_pri|
Line 2,927 ⟶ 4,574:
}).call([2])
end
p primes(50)</langsyntaxhighlight>
 
{{out}}
Line 2,933 ⟶ 4,580:
 
===By Regular Expression===
<langsyntaxhighlight lang="ruby">def isprime(n)
'1'*n !~ /^1?$|^(11+?)\1+$/
end</langsyntaxhighlight>
 
===Prime Generators Tests===
=={{header|Run BASIC}}==
Mathematicaly basis of Prime Generators
<lang runbasic>' Test and display primes 1 .. 50
https://www.academia.edu/19786419/PRIMES-UTILS_HANDBOOK
for i = 1 TO 50
https://www.academia.edu/42734410/Improved_Primality_Testing_and_Factorization_in_Ruby_revised
if prime(i) <> 0 then print i;" ";
<syntaxhighlight lang="ruby">require "benchmark/ips"
next i
 
# the simplest PG primality test using the P3 prime generator
FUNCTION prime(n)
# reduces the number space for primes to 2/6 (33.33%) of all integers
if n < 2 then prime = 0 : goto [exit]
 
if n = 2 then prime = 1 : goto [exit]
def primep3?(n) # P3 Prime Generator primality test
if n mod 2 = 0 then prime = 0 : goto [exit]
# P3 = 6*k + {5, 7} # P3 primes candidates (pc) sequence
prime = 1
return n | 1 == 3 if n < 5 # n: 0,1,4|false, 2,3|true
for i = 3 to int(n^.5) step 2
return false if n.gcd(6) != 1 # 1/3 (2/6) of integers are P3 pc
if n mod i = 0 then prime = 0 : goto [exit]
p, sqrtn = 5, Integer.sqrt(n) # first P3 sequence value
next i
until p > sqrtn
[exit]
return false if n % p == 0 || n % (p + 2) == 0 # if n is composite
END FUNCTION</lang>
p += 6 # first prime candidate for next kth residues group
2 3 5 7 11 13 17 19 23 25 29 31 37 41 43 47 49
end
true
end
 
# PG primality test using the P5 prime generator
# reduces the number space for primes to 8/30 (26.67%) of all integers
 
def primep5?(n) # P5 Prime Generator primality test
# P5 = 30*k + {7,11,13,17,19,23,29,31} # P5 primes candidates sequence
return [2, 3, 5].include?(n) if n < 7 # for small and negative values
return false if n.gcd(30) != 1 # 4/15 (8/30) of integers are P5 pc
p, sqrtn = 7, Integer.sqrt(n) # first P5 sequence value
until p > sqrtn
return false if # if n is composite
n % (p) == 0 || n % (p+4) == 0 || n % (p+6) == 0 || n % (p+10) == 0 ||
n % (p+12) == 0 || n % (p+16) == 0 || n % (p+22) == 0 || n % (p+24) == 0
p += 30 # first prime candidate for next kth residues group
end
true
end
 
# PG primality test using the P7 prime generator
# reduces the number space for primes to 48/210 (22.86%) of all integers
 
def primep7?(n)
# P7 = 210*k + {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,121,127,131,137,139,143,149,151,157,163,
# 167,169,173,179,181,187,191,193,197,199,209,211}
return [2, 3, 5, 7].include?(n) if n < 11
return false if n.gcd(210) != 1 # 8/35 (48/210) of integers are P7 pc
p, sqrtn = 11, Integer.sqrt(n) # first P7 sequence value
until p > sqrtn
return false if
n % (p) == 0 || n % (p+2) == 0 || n % (p+6) == 0 || n % (p+8) == 0 ||
n % (p+12) == 0 || n % (p+18) == 0 || n % (p+20) == 0 || n % (p+26) == 0 ||
n % (p+30) == 0 || n % (p+32) == 0 || n % (p+36) == 0 || n % (p+42) == 0 ||
n % (p+48) == 0 || n % (p+50) == 0 || n % (p+56) == 0 || n % (p+60) == 0 ||
n % (p+62) == 0 || n % (p+68) == 0 || n % (p+72) == 0 || n % (p+78) == 0 ||
n % (p+86) == 0 || n % (p+90) == 0 || n % (p+92) == 0 || n % (p+96) == 0 ||
n % (p+98) == 0 || n % (p+102) == 0 || n % (p+110) == 0 || n % (p+116) == 0 ||
n % (p+120) == 0 || n % (p+126) == 0 || n % (p+128) == 0 || n % (p+132) == 0 ||
n % (p+138) == 0 || n % (p+140) == 0 || n % (p+146) == 0 || n % (p+152) == 0 ||
n % (p+156) == 0 || n % (p+158) == 0 || n % (p+162) == 0 || n % (p+168) == 0 ||
n % (p+170) == 0 || n % (p+176) == 0 || n % (p+180) == 0 || n % (p+182) == 0 ||
n % (p+186) == 0 || n % (p+188) == 0 || n % (p+198) == 0 || n % (p+200) == 0
p += 210 # first prime candidate for next kth residues group
end
true
end
 
# Benchmarks to test for various size primes
 
p = 541
Benchmark.ips do |b|
print "\np = #{p}"
b.report("primep3?") { primep3?(p) }
b.report("primep5?") { primep5?(p) }
b.report("primep7?") { primep7?(p) }
b.compare!
puts
end
 
p = 1000003
Benchmark.ips do |b|
print "\np = #{p}"
b.report("primep3?") { primep3?(p) }
b.report("primep5?") { primep5?(p) }
b.report("primep7?") { primep7?(p) }
b.compare!
puts
end
 
p = 4294967291 # largest prime < 2**32
Benchmark.ips do |b|
print "\np = #{p}"
b.report("primep3?") { primep3?(p) }
b.report("primep5?") { primep5?(p) }
b.report("primep7?") { primep7?(p) }
b.compare!
puts
end
 
p = (10 ** 16) * 2 + 3
Benchmark.ips do |b|
print "\np = #{p}"
b.report("primep3?") { primep3?(p) }
b.report("primep5?") { primep5?(p) }
b.report("primep7?") { primep7?(p) }
b.compare!
puts
end</syntaxhighlight>
{{out}}
<pre>p = 541
Warming up --------------------------------------
primep3? 109.893k i/100ms
primep5? 123.949k i/100ms
primep7? 44.216k i/100ms
Calculating -------------------------------------
primep3? 1.598M (± 3.4%) i/s - 8.022M in 5.025036s
primep5? 1.872M (± 6.3%) i/s - 9.420M in 5.059896s
primep7? 502.040k (± 1.2%) i/s - 2.520M in 5.020919s
 
Comparison:
primep5?: 1871959.0 i/s
primep3?: 1598489.8 i/s - 1.17x slower
primep7?: 502039.8 i/s - 3.73x slower
 
 
p = 1000003
Warming up --------------------------------------
primep3? 5.850k i/100ms
primep5? 9.013k i/100ms
primep7? 10.889k i/100ms
Calculating -------------------------------------
primep3? 59.965k (± 1.1%) i/s - 304.200k in 5.073641s
primep5? 92.561k (± 2.1%) i/s - 468.676k in 5.065709s
primep7? 109.335k (± 0.8%) i/s - 555.339k in 5.079549s
 
Comparison:
primep7?: 109334.7 i/s
primep5?: 92561.4 i/s - 1.18x slower
primep3?: 59964.5 i/s - 1.82x slower
 
 
p = 4294967291
Warming up --------------------------------------
primep3? 92.000 i/100ms
primep5? 148.000 i/100ms
primep7? 184.000 i/100ms
Calculating -------------------------------------
primep3? 926.647 (± 1.1%) i/s - 4.692k in 5.064067s
primep5? 1.480k (± 1.7%) i/s - 7.400k in 5.001399s
primep7? 1.804k (± 1.0%) i/s - 9.200k in 5.099110s
 
Comparison:
primep7?: 1804.4 i/s
primep5?: 1480.0 i/s - 1.22x slower
primep3?: 926.6 i/s - 1.95x slower
 
 
p = 20000000000000003
Warming up --------------------------------------
primep3? 1.000 i/100ms
primep5? 1.000 i/100ms
primep7? 1.000 i/100ms
Calculating -------------------------------------
primep3? 0.422 (± 0.0%) i/s - 3.000 in 7.115929s
primep5? 0.671 (± 0.0%) i/s - 4.000 in 5.957077s
primep7? 0.832 (± 0.0%) i/s - 5.000 in 6.007834s
 
Comparison:
primep7?: 0.8 i/s
primep5?: 0.7 i/s - 1.24x slower
primep3?: 0.4 i/s - 1.97x slower
</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn is_prime(n: u64) -> bool {
match n {
0 | 1 => false,
Line 2,972 ⟶ 4,774:
println!("{} ", i);
}
}</langsyntaxhighlight>
{{out}}
<pre>2 3 5 7 11 13 17 19 23 29 </pre>
 
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">define is_prime(n)
{
if (n == 2) return(1);
Line 3,001 ⟶ 4,804:
print(strjoin(list_to_array(lst), ", "));
}
ptest();</langsyntaxhighlight>
{{out}}
"2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61"
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">data primes;
do n=1 to 1000;
link primep;
Line 3,026 ⟶ 4,829:
return;
keep n;
run;</langsyntaxhighlight>
 
=={{header|Scala}}==
===Simple version===
<langsyntaxhighlight Scalalang="scala"> def isPrime(n: Int) =
n > 1 && (Iterator.from(2) takeWhile (d => d * d <= n) forall (n % _ != 0))</langsyntaxhighlight>
===Accelerated version [[functional_programming|FP]] and parallel runabled===
// {{Out}}Best seen running in your browser [https://scastie.scala-lang.org/1RLimJrRQUqkXWkUwUxgYg Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">object IsPrimeTrialDivision extends App {
def isPrime(n: Long) =
n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) &&
Line 3,053 ⟶ 4,856:
println("All done")
 
}</langsyntaxhighlight>
===Accelerated version [[functional_programming|FP]], tail recursion===
Tests 1.3 M numbers against OEIS prime numbers.
<langsyntaxhighlight Scalalang="scala">import scala.annotation.tailrec
import scala.io.Source
 
Line 3,077 ⟶ 4,880:
for (i <- 0 to 1299709) assert(isPrime(i) == oeisPrimes.contains(i.toString), s"Wrong $i")
 
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<langsyntaxhighlight lang="scheme">(define (prime? number)
(define (*prime? divisor)
(or (> (* divisor divisor) number)
Line 3,087 ⟶ 4,890:
(*prime? (+ divisor 1)))))
(and (> number 1)
(*prime? 2)))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="scheme">; twice faster, testing only odd divisors
(define (prime? n)
(if (< n 4) (> n 1)
Line 3,096 ⟶ 4,899:
(or (> (* k k) n)
(and (positive? (remainder n k))
(loop (+ k 2))))))))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const func boolean: isPrime (in integer: number) is func
result
var boolean: prime is FALSE;
Line 3,115 ⟶ 4,918:
prime := testNum > upTo;
end if;
end func;</langsyntaxhighlight>
Original source: [http://seed7.sourceforge.net/algorith/math.htm#is_prime]
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program trial_division;
print({n : n in {1..100} | prime n});
 
op prime(n);
return n>=2 and not exists d in {2..floor sqrt n} | n mod d = 0;
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}}==
<langsyntaxhighlight lang="ruby">func is_prime(a) {
given (a) {
when (2) { true }
Line 3,125 ⟶ 4,938:
default { 3 .. a.isqrt -> any { .divides(a) } -> not }
}
}</langsyntaxhighlight>
{{trans|Perl}}
Alternative version, excluding multiples of 2 and 3:
<langsyntaxhighlight lang="ruby">func is_prime(n) {
return (n >= 2) if (n < 4)
return false if (n%%2 || n%%3)
Line 3,135 ⟶ 4,948:
}
return true
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">| isPrime |
isPrime := [:n |
n even ifTrue: [ ^n=2 ]
Line 3,147 ⟶ 4,960:
^true
]
]</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4">define('isprime(n)i,max') :(isprime_end)
isprime isprime = n
le(n,1) :s(freturn)
Line 3,158 ⟶ 4,971:
isp1 i = le(i + 2,max) i + 2 :f(return)
eq(remdr(n,i),0) :s(freturn)f(isp1)
isprime_end</langsyntaxhighlight>
===By Patterns===
Using the Abigail regex transated to Snobol patterns.
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('rprime(n)str,pat1,pat2,m1') :(end_rprime)
rprime str = dupl('1',n); rprime = n
pat1 = ('1' | '')
Line 3,172 ⟶ 4,985:
n = lt(n,50) n + 1 :s(loop)
output = rprimes
end</langsyntaxhighlight>
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "prime" );
pragma annotate( description, "Write a boolean function that tells whether a given" );
pragma annotate( description, "integer is prime. Remember that 1 and all" );
pragma annotate( description, "non-positive numbers are not prime. " );
pragma annotate( see_also, "http://rosettacode.org/wiki/Primality_by_trial_division" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure prime is
 
function is_prime(item : positive) return boolean is
result : boolean := true;
test : natural;
begin
if item /= 2 and item mod 2 = 0 then
result := false;
else
test := 3;
while test < natural( numerics.sqrt( item ) ) loop
if natural(item) mod test = 0 then
result := false;
exit;
end if;
test := @ + 2;
end loop;
end if;
return result;
end is_prime;
 
number : positive;
result : boolean;
 
begin
number := 6;
result := is_prime( number );
put( number ) @ ( " : " ) @ ( result );
new_line;
 
number := 7;
result := is_prime( number );
put( number ) @ ( " : " ) @ ( result );
new_line;
 
number := 8;
result := is_prime( number );
put( number ) @ ( " : " ) @ ( result );
new_line;
end prime;</syntaxhighlight>
 
=={{header|SQL}}==
{{works with|T-SQL}}
<langsyntaxhighlight lang="tsql">declare @number int
set @number = 514229 -- number to check
 
Line 3,206 ⟶ 5,073:
' is prime'
end primalityTest
option (maxrecursion 0)</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun is_prime n =
if n = 2 then true
else if n < 2 orelse n mod 2 = 0 then false
Line 3,218 ⟶ 5,085:
else loop (k+2)
in loop 3
end</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
 
extension Int {
Line 3,237 ⟶ 5,104:
}
}
}</langsyntaxhighlight>
 
A version that works with Swift 5.x and probably later. Does not need to import Foundation
 
<syntaxhighlight lang="swift">
extension Int
{
func isPrime() -> Bool
{
if self < 3
{
return self == 2
}
else
{
let upperLimit = Int(Double(self).squareRoot())
return !self.isMultiple(of: 2) && !stride(from: 3, through: upperLimit, by: 2)
.contains(where: { factor in self.isMultiple(of: factor) })
}
}
}
</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc is_prime n {
if {$n <= 1} {return false}
if {$n == 2} {return true}
Line 3,248 ⟶ 5,136:
}
return true
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Prompt A
If A=2:Then
Disp "PRIME"
Stop
End
If (fPart(A/2)=0 and A>0) or A<2:Then
Disp "NOT PRIME"
Stop
End
1→P
For(B,3,int(√(A)))
If FPart(A/B)=0:Then
0→P
√(A)→B
End
B+1→B
End
If P=1:Then
Disp "PRIME"
Else
Disp "NOT PRIME"
End
 
=={{header|uBasic/4tH}}==
<lang>10 LET n=0: LET p=0
20 INPUT "Enter number: ";n
30 LET p=0 : IF n>1 THEN GOSUB 1000
40 IF p=0 THEN PRINT n;" is not prime!"
50 IF p#0 THEN PRINT n;" is prime!"
60 GOTO 10
1000 REM ***************
1001 REM * PRIME CHECK *
1002 REM ***************
1010 LET p=0
1020 IF (n%2)=0 THEN RETURN
1030 LET p=1 : PUSH n,0 : GOSUB 9030
1040 FOR i=3 TO POP() STEP 2
1050 IF (n%i)=0 THEN LET p=0: PUSH n,0 : GOSUB 9030 : LET i=POP()
1060 NEXT i
1070 RETURN
9030 Push ((10^(Pop()*2))*Pop()) : @(255)=Tos()
9040 Push (@(255) + (Tos()/@(255)))/2
If Abs(@(255)-Tos())<2 Then @(255)=Pop() : If Pop() Then Push @(255) : Return
@(255) = Pop() : Goto 9040
REM ** This is an integer SQR subroutine. Output is scaled by 10^(TOS()).</lang>
 
=={{header|UNIX Shell}}==
Line 3,306 ⟶ 5,144:
{{works with|pdksh}}
{{works with|zsh}}
<langsyntaxhighlight lang="bash">function primep {
typeset n=$1 p=3
(( n == 2 )) && return 0 # 2 is prime.
Line 3,320 ⟶ 5,158:
done
return 0 # Yes, n is prime.
}</langsyntaxhighlight>
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">primep() {
set -- "$1" 3
test "$1" -eq 2 && return 0 # 2 is prime.
Line 3,336 ⟶ 5,174:
done
return 0 # Yes, n is prime.
}</langsyntaxhighlight>
 
=={{header|Ursala}}==
Excludes even numbers, and loops only up to the approximate square root or until a factor is found.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
prime = ~<{0,1}&& -={2,3}!| ~&h&& (all remainder)^Dtt/~& iota@K31</langsyntaxhighlight>
Test program to try it on a few numbers:
<langsyntaxhighlight Ursalalang="ursala">#cast %bL
 
test = prime* <5,6,7></langsyntaxhighlight>
{{out}}
<true,false,true>
Line 3,353 ⟶ 5,191:
=={{header|V}}==
{{trans|Joy}}
<langsyntaxhighlight lang="v">[prime?
2
[[dup * >] [true] [false] ifte [% 0 >] dip and]
[succ]
while
dup * <].</langsyntaxhighlight>
{{out|Using it}}
<langsyntaxhighlight lang="v">|11 prime?
=true
|4 prime?
=false</langsyntaxhighlight>
 
=={{header|VBA}}==
<lang vb>Option Explicit
 
=={{header|Verilog}}==
Sub FirstTwentyPrimes()
<syntaxhighlight lang="Verilog">module main;
Dim count As Integer, i As Long, t(19) As String
integer i, k;
Do
initial begin
i = i + 1
$display("Prime numbers between 0 and 100:");
If IsPrime(i) Then
for(i = 2; i <= t(count)99; i= i+1) begin
count k= count + 1i;
Endif(i[0] If!= 1'b0) begin
if(k==3 | k==5 | k==7 | k==11 | k==13 | k==17 | k==19) $write(i);
Loop While count <= UBound(t)
else if(k%3==0 | k%5==0 | k%7==0 | k%11==0 | k%13==0 | k%17==0 | k%19==0) $write("");
Debug.Print Join(t, ", ")
else $write(i);
End Sub
end
if(i==10'b00 | i==10'b010) $write(i);
end
$finish;
end
endmodule</syntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Zig">
import math
 
const numbers = [5, 3, 14, 19, 25, 59, 88]
 
fn main() {
for num in numbers {
println("${num} is a prime number? " + if is_prime(num) == true {'yes'} else {'no'})
}
}
 
fn is_prime(num int) bool {
if num <= 1 {return false}
if num % 2 == 0 && num != 2 {return false}
for idx := 3; idx <= math.floor(num / 2) - 1; idx += 2 {
if num % idx == 0 {return false}
}
return true
}
</syntaxhighlight>
 
Function IsPrime(Nb As Long) As Boolean
If Nb = 2 Then
IsPrime = True
ElseIf Nb < 2 Or Nb Mod 2 = 0 Then
Exit Function
Else
Dim i As Long
For i = 3 To Sqr(Nb) Step 2
If Nb Mod i = 0 Then Exit Function
Next
IsPrime = True
End If
End Function</lang>
{{out}}
<pre>
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
5 is a prime number? yes
3 is a prime number? yes
14 is a prime number? no
19 is a prime number? yes
25 is a prime number? no
59 is a prime number? yes
88 is a prime number? no
</pre>
 
=={{header|VBScriptWren}}==
{{translibheader|BASICWren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
<lang vb>Function IsPrime(n)
 
If n = 2 Then
var isPrime = Fn.new { |n|
IsPrime = True
ElseIf n <= 1 Orif (n Mod< 2) = 0return Thenfalse
if (n%2 == 0) return n == 2
IsPrime = False
var p = 3
Else
while (p * p <= n) {
IsPrime = True
For i = 3 To Int(Sqr if (n)%p == 0) Stepreturn 2false
If n Mod i p = 0p + Then2
}
IsPrime = False
return true
Exit For
}
End If
 
Next
var tests = [2, 5, 12, 19, 57, 61, 97]
End If
System.print("Are the following prime?")
End Function
for (test in tests) {
Fmt.print("$2d -> $y", test, isPrime.call(test))
}</syntaxhighlight>
 
For n = 1 To 50
If IsPrime(n) Then
WScript.StdOut.Write n & " "
End If
Next</lang>
{{out}}
<pre>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Are the following prime?
2 -> yes
5 -> yes
12 -> no
19 -> yes
57 -> no
61 -> yes
97 -> yes
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func Prime(N); \Return 'true' if N is a prime number
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
 
func Prime(N); \Return 'true' if N is a prime number
int N;
int I;
[if N <= 1 then return false;
for I:= 32 to sqrt(N) do
if rem(N/I) = 0 then return false;
return true;
]; \Prime
 
int Num;
Line 3,438 ⟶ 5,302:
Text(0, if Prime(Num) then "is " else "not ");
Text(0, "prime^M^J");
until Num = 0</langsyntaxhighlight>
{{out}}
<pre>777777777
Line 3,449 ⟶ 5,313:
=={{header|zkl}}==
The Method filter1 stops at the first non False result, which, if there is one, is the first found diviser, thus short cutting the rest of the test
<langsyntaxhighlight lang="zkl">fcn isPrime(n){
if(n.isEven or n<2) return(n==2);
(not [3..n.toFloat().sqrt().toInt(),2].filter1('wrap(m){n%m==0}))
}</langsyntaxhighlight>
{{out}}
<pre>zkl: [1..].filter(20,isPrime)
890

edits