Jump to content

Primality by trial division: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 27:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F is_prime(n)
I n < 2
R 0B
Line 33:
I n % i == 0
R 0B
R 1B</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Primality by trial division 26/03/2017
PRIMEDIV CSECT
USING PRIMEDIV,R13 base register
Line 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}}==
<langsyntaxhighlight lang="68000devpac">isPrime:
; REG USAGE:
; D0 = input (unsigned 32-bit integer)
Line 160:
MOVEM.L (SP)+,D1-D4 ;pop D1-D4
RTS
;end of program</langsyntaxhighlight>
 
=={{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 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 367:
RETURN.
endmethod.
ENDCLASS.</langsyntaxhighlight>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun is-prime-r (x i)
(declare (xargs :measure (nfix (- x i))))
(if (zp (- (- x i) 1))
Line 379:
(defun is-prime (x)
(or (= x 2)
(is-prime-r x 2)))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC IsPrime(CARD a)
CARD i
 
Line 412:
Test(120)
Test(0)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Primality_by_trial_division.png Screenshot from Atari 8-bit computer]
Line 425:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function isPrime(n:int):Boolean
{
if(n < 2) return false;
Line 433:
if(n % i == 0) return false;
return true;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">function Is_Prime(Item : Positive) return Boolean is
Test : Natural;
begin
Line 455:
end if;
return True;
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) :
<langsyntaxhighlight 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));</langsyntaxhighlight>
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 477:
raise Program_Error with "Test_Prime failed!";
end if;
end Test_Prime;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 484:
{{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 493:
OD;
printf($l$)
)</langsyntaxhighlight>
{{out}}
The primes up to 100 are:
Line 499:
 
=={{header|ALGOL-M}}==
<langsyntaxhighlight lang="algol">
BEGIN
 
Line 552:
 
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 560:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">% returns true if n is prime, false otherwise %
% uses trial division %
logical procedure isPrime ( integer value n ) ;
Line 576:
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
Line 587:
=={{header|AppleScript}}==
 
<langsyntaxhighlight lang="applescript">on isPrime(n)
if (n < 3) then return (n is 2)
if (n mod 2 is 0) then return false
Line 602:
if (isPrime(n)) then set end of output to n
end repeat
return output</langsyntaxhighlight>
 
Or eliminating multiples of 3 at the start as well as those of 2:
 
<langsyntaxhighlight lang="applescript">on isPrime(n)
if (n < 4) then return (n > 1)
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
Line 621:
if (isPrime(n)) then set end of output to n
end repeat
return output</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight 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}</langsyntaxhighlight>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">isPrime?: function [n][
if n=2 -> return true
if n=3 -> return true
Line 642:
loop 1..20 'i [
print ["isPrime?" i "=" isPrime? i ]
]</langsyntaxhighlight>
 
{{out}}
Line 669:
=={{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 676:
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 712:
Return True
EndFunc
main()</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 719:
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 726:
}
 
{print prime($1)}</langsyntaxhighlight>
 
=={{header|B}}==
Line 732:
{{trans|C}}
{{works with|B as on PDP7/UNIX0|(proto-B?)}}
<langsyntaxhighlight Blang="b">isprime(n) {
auto p;
if(n<2) return(0);
Line 742:
}
return(1);
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 748:
{{works with|QuickBasic|4.5}}
Returns 1 for prime, 0 for non-prime
<langsyntaxhighlight QBasiclang="qbasic">FUNCTION prime% (n!)
STATIC i AS INTEGER
IF n = 2 THEN
Line 769:
FOR n = 1 TO 50
IF prime(n) = 1 THEN PRINT n;
NEXT n</langsyntaxhighlight>
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
 
==={{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 789:
230 NEXT
240 END IF
250 END DEF</langsyntaxhighlight>
 
==={{header|True BASIC}}===
{{trans|BASIC}}
<langsyntaxhighlight lang="qbasic">FUNCTION isPrime (n)
IF n = 2 THEN
LET isPrime = 1
Line 812:
IF isPrime(n) = 1 THEN PRINT n;
NEXT n
END</langsyntaxhighlight>
 
==={{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 831:
1060 NEXT i
1070 RETURN
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 841:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="freebasic">for i = 1 to 99
if isPrime(i) then print string(i); " ";
next i
Line 855:
end while
return True
end function</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> FOR i% = -1 TO 100
IF FNisprime(i%) PRINT ; i% " is prime"
NEXT
Line 871:
IF n% MOD t% = 0 THEN = FALSE
NEXT
= TRUE</langsyntaxhighlight>
{{out}}
<pre>2 is prime
Line 900:
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">/* Return 1 if n is prime, 0 otherwise */
define p(n) {
auto i
Line 911:
}
return(1)
}</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let sqrt(s) =
Line 941:
if isprime(i) then writef("%N ",i)
wrch('*N')
$)</langsyntaxhighlight>
{{out}}
<pre>2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97</pre>
Line 950:
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 970:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat"> ( prime
= incs n I inc
. 4 2 4 2 4 6 2 6:?incs
Line 991:
)
)
& ;</langsyntaxhighlight>
{{out}}
<pre>100000000003
Line 1,002:
 
=={{header|Brainf***}}==
<langsyntaxhighlight lang="bf">>->,[.>,]>-<++++++[-<+[---------<+]->+[->+]-<]>+<-<+[-<+]>>+[-<[->++++++++++<]>>
+]++++[->++++++++<]>.<+++++++[->++++++++++<]>+++.++++++++++.<+++++++++[->-------
--<]>--.[-]<<<->[->+>+<<]>>-[+<[[->>+>>+<<<<]>>[-<<+>>]<]>>[->-[>+>>]>[+[-<+>]>>
>]<<<<<]>[-]>[>+>]<<[-]+[-<+]->>>--]<[->+>+<<]>>>>>>>[-<<<<<->>>>>]<<<<<--[>++++
++++++[->+++++++++++<]>.+.+++++.>++++[->++++++++<]>.>]++++++++++[->+++++++++++<]
>++.++.---------.++++.--------.>++++++++++.</langsyntaxhighlight>
Explanation:
<langsyntaxhighlight lang="bf">>
->,[.>,]>-<++++++[-<+[---------<+]->+[->+]-<]>+<-<+[-<+]>>+[-<[->++++++++++<]>>+]< takes input
>++++[->++++++++<]>.<+++++++[->++++++++++<]>+++.++++++++++.<+++++++++[->---------<]>--.[-]<< " is "
Line 1,016:
<[->+>+<<]>>>>>>>[-<<<<<->>>>>]<<<<<--
[>++++++++++[->+++++++++++<]>.+.+++++.>++++[->++++++++<]>.>] "not "
++++++++++[->+++++++++++<]>++.++.---------.++++.--------.>++++++++++. "prime" new line</langsyntaxhighlight>
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 1,026:
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 1,045:
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 1,054:
if (n % i == 0) return false;
return true;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <cmath>
 
bool is_prime(unsigned int n)
Line 1,069:
return false;
return true;
}</langsyntaxhighlight>
 
=={{header|Chapel}}==
{{trans|C++}}
<langsyntaxhighlight lang="chapel">proc is_prime(n)
{
if n == 2 then
Line 1,083:
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 1,096:
(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 1,108:
(not-any? (partial divides? x)
(take-while (partial >= (Math/sqrt x)) primes))))
</syntaxhighlight>
</lang>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">isqrt = proc (s: int) returns (int)
x0: int := s/2
if x0=0 then return(s) end
Line 1,138:
end
end
end start_up</langsyntaxhighlight>
{{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 1,173:
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 1,183:
message(STATUS "${i} is _not_ prime.")
endif(b)
endforeach(i)</langsyntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> Identification Division.
Program-Id. Primality-By-Subdiv.
 
Line 1,223:
 
Goback
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">is_prime = (n) ->
# simple prime detection using trial division, works
# for all integers
Line 1,237:
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 1,260:
(format t "~d is not a prime number" n)))
(prime 7)
(prime 8)</langsyntaxhighlight>
Output:
7 is a prime number
Line 1,269:
https://www.academia.edu/19786419/PRIMES-UTILS_HANDBOOK
https://www.academia.edu/42734410/Improved_Primality_Testing_and_Factorization_in_Ruby_revised
<langsyntaxhighlight lang="ruby">require "big"
require "benchmark"
 
Line 1,392:
b.report("primep7?") { primep7?(p) }
puts
end</langsyntaxhighlight>
{{out}}
<pre>p = 541
Line 1,422:
=={{header|D}}==
===Simple Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.math;
 
bool isPrime1(in int n) pure nothrow {
Line 1,438:
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 1,467:
 
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,486:
void main() {
iota(2, 40).filter!isPrime3.writeln;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
=== First ===
<langsyntaxhighlight Delphilang="delphi">function IsPrime(aNumber: Integer): Boolean;
var
I: Integer;
Line 1,507:
Break;
end;
end;</langsyntaxhighlight>
 
=== Second ===
<langsyntaxhighlight Delphilang="delphi">function IsPrime(const x: integer): Boolean;
var
i: integer;
Line 1,524:
until i > Sqrt(x);
Result := True;
end;</langsyntaxhighlight>
 
=={{header|E}}==
{{trans|D}}
<langsyntaxhighlight lang="e">def isPrime(n :int) {
if (n == 2) {
return true
Line 1,543:
return true
}
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">(lib 'sequences)
 
;; Try divisors iff n = 2k + 1
Line 1,573:
(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,631:
end
 
end</langsyntaxhighlight>
<pre>False
True
Line 1,641:
=={{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,651:
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]
Line 1,657:
=={{header|Emacs Lisp}}==
{{libheader|cl-lib}}
<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,694:
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,717:
END FOR
 
END PROGRAM</langsyntaxhighlight>
{{out}}
2 is prime
Line 1,746:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function is_prime(integer n)
if n<=2 or remainder(n,2)=0 then
return 0
Line 1,757:
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,785:
[<Test>]
let ``Validate that 277 is prime`` () =
isPrime 277 |> should equal true</langsyntaxhighlight>
{{out}}
> isPrime 1111111111111111111UL;;
Line 1,791:
 
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,798:
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,818:
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,828:
{ [ 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.
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
FUNCTION ISPRIME(n AS INTEGER) AS INTEGER
Line 1,875:
NEXT
 
PAUSE</langsyntaxhighlight>
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Line 1,882:
=={{header|Forth}}==
 
<langsyntaxhighlight lang="forth">: prime? ( n -- f )
dup 2 < if drop false
else dup 2 = if drop true
Line 1,892:
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,914:
END DO
END IF
END FUNCTION</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isPrime(n As Integer) As Boolean
Line 1,939:
Print : Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,946:
=={{header|Frink}}==
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!
<langsyntaxhighlight lang="frink">isPrimeByTrialDivision[x] :=
{
for p = primes[]
Line 1,957:
return true
}</langsyntaxhighlight>
 
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import math.sqrt
 
def
Line 1,969:
| otherwise = (3..int(sqrt(n)) by 2).forall( (/|n) )
 
(10^10..10^10+50).filter( isPrime ).foreach( println )</langsyntaxhighlight>
{{out}}
10000000019
Line 1,975:
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">window 1, @"Primality By Trial Division", (0,0,480,270)
 
local fn isPrime( n as long ) as Boolean
Line 2,001:
next
 
HandleEvents</langsyntaxhighlight>
Output:
Prime numbers between 0 and 1000:
Line 2,024:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=85fbc7936b17b3009af282752aa29df7 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">'Reworked from the BBC Basic example
 
Public Sub Main()
Line 2,049:
Return bReturn
 
End</langsyntaxhighlight>
Output:
<pre>1 is prime
Line 2,064:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">IsPrimeTrial := function(n)
local k, m;
if n < 5 then
Line 2,084:
 
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 2,101:
}
return true
}</langsyntaxhighlight>
 
Or, using recursion:
 
<langsyntaxhighlight lang="go">func IsPrime(n int) bool {
if n < 0 { n = -n }
if n <= 2 {
Line 2,118:
}
return true
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def isPrime = {
it == 2 ||
it > 1 &&
Line 2,127:
}
 
(0..20).grep(isPrime)</langsyntaxhighlight>
{{out}}
[2, 3, 5, 7, 11, 13, 17, 19]
Line 2,133:
=={{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 2,142:
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 2,169:
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 2,195:
}
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 2,214:
return true;
}
}</langsyntaxhighlight>
 
=={{header|Joy}}==
Line 2,249:
=={{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 2,266:
else
println("The function does not accurately calculate primes.")
end</langsyntaxhighlight>
{{out}}
The primes <= 100 are:
Line 2,272:
 
=={{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 2,288:
// 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
Line 2,296:
{{trans|Go}}
{{works with|langur|0.8.2}}
<langsyntaxhighlight lang="langur">val .isPrime = f(.i) {
val .n = abs(.i)
if .n <= 2: return .n == 2
Line 2,310:
}
 
writeln where .isPrime, series 100</langsyntaxhighlight>
 
=== Functional ===
Line 2,319:
 
{{works with|langur|0.8.1}}
<langsyntaxhighlight 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</langsyntaxhighlight>
 
{{out}}
Line 2,328:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">print "Rosetta Code - Primality by trial division"
print
[start]
Line 2,344:
next i
isPrime=1
end function</langsyntaxhighlight>
{{out}}
<pre>Rosetta Code - Primality by trial division
Line 2,356:
 
=={{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 2,363:
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 2,379:
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 2,396:
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 2,411:
 
return true
end</langsyntaxhighlight>
Type of number Decimal.
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Inventory Known1=2@, 3@
IsPrime=lambda Known1 (x as decimal) -> {
Line 2,446:
Print
Print "Found ";count;" primes"
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`testnext',
`ifelse(eval($2*$2>$1),1,
1,
Line 2,463:
 
isprime(9)
isprime(11)</langsyntaxhighlight>
{{out}}
0
Line 2,470:
=={{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 2,485:
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,519:
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,551:
((true) (_prime?))
) case
) :prime?</langsyntaxhighlight>
 
=={{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|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">ISPRIME(N)
QUIT:(N=2) 1
NEW I,R
Line 2,566:
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,580:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
Line 2,645:
 
method isFalse public static returns boolean
return \isTrue</langsyntaxhighlight>
{{out}}
<pre>$ java -cp . RCPrimality
Line 2,679:
===[[#REXX|Rexx]] version reimplemented in [[NetRexx]]===
{{trans|REXX}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
Line 2,710:
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.
<langsyntaxhighlight lang="newlisp">; Here are some simpler functions to help us:
 
(define (divisible? larger-number smaller-number)
Line 2,752:
 
(println (filter is-prime? (sequence 1 100)))
(exit)</langsyntaxhighlight>
 
{{Output}}
Line 2,759:
=={{header|Nim}}==
Here are three ways to test primality using trial division.
<langsyntaxhighlight lang="nim">import sequtils, math
 
proc prime(a: int): bool =
Line 2,778:
 
for i in 2..30:
echo i, " ", prime(i)</langsyntaxhighlight>
 
{{out}}
Line 2,812:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">function : IsPrime(n : Int) ~ Bool {
if(n <= 1) {
return false;
Line 2,824:
return true;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let is_prime n =
if n = 2 then true
else if n < 2 || n mod 2 = 0 then false
Line 2,835:
else if n mod k = 0 then false
else loop (k+2)
in loop 3</langsyntaxhighlight>
 
=={{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,863:
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,872:
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,887:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (prime? number)
(define max (sqrt number))
Line 2,899:
(> (modulo number 2) 0)
(loop 3))))
</syntaxhighlight>
</lang>
Testing:
<langsyntaxhighlight lang="scheme">
; first prime numbers less than 100
(for-each (lambda (n)
Line 2,921:
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,933:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz"> fun {Prime N}
local IPrime in
fun {IPrime N Acc}
Line 2,944:
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,sqrtint(n),
Line 2,960:
);
1
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{trans|BASIC}}
<langsyntaxhighlight Pascallang="pascal">program primes;
 
function prime(n: integer): boolean;
Line 2,992:
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 3,010:
write(actPrime,' ');
until nextPrime > 50;
end.</langsyntaxhighlight>
;Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Line 3,016:
=={{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 3,037:
my $s = 0;
$s += !!isprime($_) for 1..100000;
print "Pi(100,000) = $s\n";</langsyntaxhighlight>
===By Regular Expression===
Line 3,043:
 
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}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<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>
Line 3,062:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,069:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
function prime($a) {
if (($a % 2 == 0 && $a != 2) || $a < 2)
Line 3,083:
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===
<langsyntaxhighlight Picatlang="picat">is_prime1(N) =>
if N == 2 then
true
Line 3,103:
N mod I > 0
end
end.</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight Picatlang="picat">is_prime2(N) =>
(N == 2 ; is_prime2b(N,3)).
 
Line 3,118:
;
is_prime2b(N,Div+2)
).</langsyntaxhighlight>
 
===Functional===
<langsyntaxhighlight Picatlang="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).</langsyntaxhighlight>
 
===Generator approach===
Line 3,134:
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.
<langsyntaxhighlight Picatlang="picat">prime2(2).
prime2(N) :-
between(3, 2**156+1, N),
Line 3,140:
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.</langsyntaxhighlight>
 
===Test===
<langsyntaxhighlight Picatlang="picat">go =>
println([I : I in 1..100, is_prime1(I)]),
nl,
Line 3,150:
println([10**P,Primes.len])
end,
nl.</langsyntaxhighlight>
 
 
Line 3,172:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de prime? (N)
(or
(= N 2)
Line 3,181:
(for (D 3 T (+ D 2))
(T (> D S) T)
(T (=0 (% N D)) NIL) ) ) ) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">is_prime: procedure (n) returns (bit(1));
declare n fixed (15);
declare i fixed (10);
Line 3,196:
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.
<langsyntaxhighlight lang="pli">100H: /* TEST FOR PRIMALITY BY TRIAL DIVISION */
 
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
Line 3,258:
CALL PR$NL;
 
EOF</langsyntaxhighlight>
{{out}}
<pre>
Line 3,265:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function isPrime ($n) {
if ($n -eq 1) {$false}
Line 3,275:
}
}
1..15 | foreach{"isPrime $_ : $(isPrime $_)"}</langsyntaxhighlight>
<b>Output:</b>
<pre>isPrime 1 : False
Line 3,295:
=={{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 3,301:
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 3,320:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.i IsPrime(n)
Protected k
 
Line 3,338:
 
ProcedureReturn #True
EndProcedure</langsyntaxhighlight>
 
=={{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 3,364:
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 3,374:
>>> # 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 3,386:
2 -> true
N -> false where (= 0 (MOD N 2))
N -> (prime?-0 3 N))</langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 3,392:
<code>sqrt</code> is defined at [[Isqrt (integer square root) of X#Quackery]].
 
<langsyntaxhighlight Quackerylang="quackery"> [ dup 4 < iff [ 1 > ] done
dup 1 & not iff [ drop false ] done
true swap dup sqrt
Line 3,400:
[ dip not conclude ] ]
drop ] is isprime ( n --> b )
</syntaxhighlight>
</lang>
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">is.prime <- function(n) n == 2 || n > 2 && n %% 2 == 1 && (n < 9 || all(n %% seq(3, floor(sqrt(n)), 2) > 0))
 
which(sapply(1:100, is.prime))
# [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</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (prime? number)
Line 3,416:
((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 3,433:
}
 
say "$_ is{ "n't" x !prime($_) } prime." for 1 .. 100;</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">prime?: func [n] [
case [
n = 2 [ true ]
Line 3,447:
]
]
]</langsyntaxhighlight>
 
<langsyntaxhighlight REBOLlang="rebol">repeat i 100 [ print [i prime? i]]</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 3,462:
<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 3,482:
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 3,516:
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 3,537:
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 3,544:
<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 3,592:
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 3,607:
if (num % i = 0) return 0 ok
next
return 1</langsyntaxhighlight>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def prime(a)
if a == 2
true
Line 3,620:
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 3,632:
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 3,645:
}).call([2])
end
p primes(50)</langsyntaxhighlight>
 
{{out}}
Line 3,651:
 
===By Regular Expression===
<langsyntaxhighlight lang="ruby">def isprime(n)
'1'*n !~ /^1?$|^(11+?)\1+$/
end</langsyntaxhighlight>
 
===Prime Generators Tests===
Line 3,659:
https://www.academia.edu/19786419/PRIMES-UTILS_HANDBOOK
https://www.academia.edu/42734410/Improved_Primality_Testing_and_Factorization_in_Ruby_revised
<langsyntaxhighlight lang="ruby">require "benchmark/ips"
 
# the simplest PG primality test using the P3 prime generator
Line 3,762:
b.compare!
puts
end</langsyntaxhighlight>
{{out}}
<pre>p = 541
Line 3,829:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">' Test and display primes 1 .. 50
for i = 1 TO 50
if prime(i) <> 0 then print i;" ";
Line 3,843:
next i
[exit]
END FUNCTION</langsyntaxhighlight>
2 3 5 7 11 13 17 19 23 25 29 31 37 41 43 47 49
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn is_prime(n: u64) -> bool {
match n {
0 | 1 => false,
Line 3,863:
println!("{} ", i);
}
}</langsyntaxhighlight>
{{out}}
<pre>2 3 5 7 11 13 17 19 23 29 </pre>
 
=={{header|S-BASIC}}==
<syntaxhighlight lang="s-basic">
<lang S-BASIC>
$lines
 
Line 3,902:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,909:
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">define is_prime(n)
{
if (n == 2) return(1);
Line 3,933:
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,958:
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,985:
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 4,009:
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 4,019:
(*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 4,028:
(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 4,047:
prime := testNum > upTo;
end if;
end func;</langsyntaxhighlight>
Original source: [http://seed7.sourceforge.net/algorith/math.htm#is_prime]
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func is_prime(a) {
given (a) {
when (2) { true }
Line 4,057:
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 4,067:
}
return true
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">| isPrime |
isPrime := [:n |
n even ifTrue: [ ^n=2 ]
Line 4,079:
^true
]
]</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4">define('isprime(n)i,max') :(isprime_end)
isprime isprime = n
le(n,1) :s(freturn)
Line 4,090:
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 4,104:
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
Line 4,110:
=={{header|SQL}}==
{{works with|T-SQL}}
<langsyntaxhighlight lang="tsql">declare @number int
set @number = 514229 -- number to check
 
Line 4,138:
' 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 4,150:
else loop (k+2)
in loop 3
end</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
 
extension Int {
Line 4,169:
}
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc is_prime n {
if {$n <= 1} {return false}
if {$n == 2} {return true}
Line 4,180:
}
return true
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 4,210:
 
=={{header|Tiny BASIC}}==
<langsyntaxhighlight lang="tinybasic"> PRINT "ENTER A NUMBER "
INPUT P
GOSUB 100
Line 4,226:
LET I = I + 1
IF I*I <= P THEN GOTO 110
RETURN</langsyntaxhighlight>
 
=={{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
Line 4,249:
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()).</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 4,257:
{{works with|pdksh}}
{{works with|zsh}}
<langsyntaxhighlight lang="bash">function primep {
typeset n=$1 p=3
(( n == 2 )) && return 0 # 2 is prime.
Line 4,271:
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 4,287:
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 4,304:
=={{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}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub FirstTwentyPrimes()
Line 4,343:
IsPrime = True
End If
End Function</langsyntaxhighlight>
{{out}}
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
Line 4,349:
=={{header|VBScript}}==
{{trans|BASIC}}
<langsyntaxhighlight lang="vb">Function IsPrime(n)
If n = 2 Then
IsPrime = True
Line 4,369:
WScript.StdOut.Write n & " "
End If
Next</langsyntaxhighlight>
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Line 4,375:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var isPrime = Fn.new { |n|
Line 4,392:
for (test in tests) {
System.print("%(Fmt.d(2, test)) -> %(isPrime.call(test) ? "yes" : "no")")
}</langsyntaxhighlight>
 
{{out}}
Line 4,407:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func Prime(N); \Return 'true' if N is a prime number
int N;
int I;
Line 4,420:
Text(0, if Prime(Num) then "is " else "not ");
Text(0, "prime^M^J");
until Num = 0</langsyntaxhighlight>
{{out}}
<pre>777777777
Line 4,431:
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="yabasic">for i = 1 to 99
if isPrime(i) print str$(i), " ";
next i
Line 4,446:
wend
return True
end sub</langsyntaxhighlight>
 
=={{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)
10,350

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.