Primality by trial division: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Joy}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 27:
=={{header|11l}}==
<
I n < 2
R 0B
Line 33:
I n % i == 0
R 0B
R 1B</
=={{header|360 Assembly}}==
<
PRIMEDIV CSECT
USING PRIMEDIV,R13 base register
Line 98:
XDEC DS CL12 temp for xdeco
YREGS
END PRIMEDIV</
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
=={{header|68000 Assembly}}==
<
; REG USAGE:
; D0 = input (unsigned 32-bit integer)
Line 160:
MOVEM.L (SP)+,D1-D4 ;pop D1-D4
RTS
;end of program</
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight 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>
=={{header|ABAP}}==
<
public
create public .
Line 367:
RETURN.
endmethod.
ENDCLASS.</
=={{header|ACL2}}==
<
(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)))</
=={{header|Action!}}==
<
CARD i
Line 412:
Test(120)
Test(0)
RETURN</
{{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}}==
<
{
if(n < 2) return false;
Line 433:
if(n % i == 0) return false;
return true;
}</
=={{header|Ada}}==
<
Test : Natural;
begin
Line 455:
end if;
return True;
end Is_Prime;</
<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) :
<
(Item /= 1 and then
(for all Test in 2..Integer(Sqrt(Float(Item))) => Item mod Test /= 0));</
As an alternative, one can use the generic function Prime_Numbers.Is_Prime, as specified in [[Prime decomposition#Ada]], which also implements trial division.
<
procedure Test_Prime is
Line 477:
raise Program_Error with "Test_Prime failed!";
end if;
end Test_Prime;</
=={{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}};
<
INT upb=100;
printf(($" The primes up to "g(-3)" are:"l$,upb));
Line 493:
OD;
printf($l$)
)</
{{out}}
The primes up to 100 are:
Line 499:
=={{header|ALGOL-M}}==
<
BEGIN
Line 552:
END
</syntaxhighlight>
{{out}}
<pre>
Line 560:
=={{header|ALGOL W}}==
<
% uses trial division %
logical procedure isPrime ( integer value n ) ;
Line 576:
end;
havePrime
end isPrime ;</
Test program:
<
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.</
{{out}}
2 3 5 7 11 13 17 19 23 29 31
Line 587:
=={{header|AppleScript}}==
<
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</
Or eliminating multiples of 3 at the start as well as those of 2:
<
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</
{{output}}
<
=={{header|Arturo}}==
<
if n=2 -> return true
if n=3 -> return true
Line 642:
loop 1..20 'i [
print ["isPrime?" i "=" isPrime? i ]
]</
{{out}}
Line 669:
=={{header|AutoHotkey}}==
[http://www.autohotkey.com/forum/topic44657.html Discussion]
<
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
}</
=={{header|AutoIt}}==
<
AutoIt Version: 3.3.8.1
Line 712:
Return True
EndFunc
main()</
=={{header|AWK}}==
Line 719:
Or more legibly, and with n <= 1 handling
<
if (n <= 1) return 0
for (d = 2; d <= sqrt(n); d++)
Line 726:
}
{print prime($1)}</
=={{header|B}}==
Line 732:
{{trans|C}}
{{works with|B as on PDP7/UNIX0|(proto-B?)}}
<
auto p;
if(n<2) return(0);
Line 742:
}
return(1);
}</
=={{header|BASIC}}==
Line 748:
{{works with|QuickBasic|4.5}}
Returns 1 for prime, 0 for non-prime
<
STATIC i AS INTEGER
IF n = 2 THEN
Line 769:
FOR n = 1 TO 50
IF prime(n) = 1 THEN PRINT n;
NEXT n</
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
==={{header|IS-BASIC}}===
<
110 FOR X=0 TO 100
120 IF PRIME(X) THEN PRINT X;
Line 789:
230 NEXT
240 END IF
250 END DEF</
==={{header|True BASIC}}===
{{trans|BASIC}}
<
IF n = 2 THEN
LET isPrime = 1
Line 812:
IF isPrime(n) = 1 THEN PRINT n;
NEXT n
END</
==={{header|ZX Spectrum Basic}}===
<
20 INPUT "Enter number: ";n
30 IF n>1 THEN GO SUB 1000
Line 831:
1060 NEXT i
1070 RETURN
</syntaxhighlight>
{{out}}
<pre>
Line 841:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<
if isPrime(i) then print string(i); " ";
next i
Line 855:
end while
return True
end function</
=={{header|BBC BASIC}}==
<
IF FNisprime(i%) PRINT ; i% " is prime"
NEXT
Line 871:
IF n% MOD t% = 0 THEN = FALSE
NEXT
= TRUE</
{{out}}
<pre>2 is prime
Line 900:
=={{header|bc}}==
<
define p(n) {
auto i
Line 911:
}
return(1)
}</
=={{header|BCPL}}==
<
let sqrt(s) =
Line 941:
if isprime(i) then writef("%N ",i)
wrch('*N')
$)</
{{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.
<
v_v#`\*:%*:*84\/*:*84::+<
v >::48*:*/\48*:*%%!#v_1^
>0"seY" >:#,_@#: "No">#0<</
{{out}} (multiple runs)
Line 970:
=={{header|Bracmat}}==
<
= incs n I inc
. 4 2 4 2 4 6 2 6:?incs
Line 991:
)
)
& ;</
{{out}}
<pre>100000000003
Line 1,002:
=={{header|Brainf***}}==
<
+]++++[->++++++++<]>.<+++++++[->++++++++++<]>+++.++++++++++.<+++++++++[->-------
--<]>--.[-]<<<->[->+>+<<]>>-[+<[[->>+>>+<<<<]>>[-<<+>>]<]>>[->-[>+>>]>[+[-<+>]>>
>]<<<<<]>[-]>[>+>]<<[-]+[-<+]->>>--]<[->+>+<<]>>>>>>>[-<<<<<->>>>>]<<<<<--[>++++
++++++[->+++++++++++<]>.+.+++++.>++++[->++++++++<]>.>]++++++++++[->+++++++++++<]
>++.++.---------.++++.--------.>++++++++++.</
Explanation:
<
->,[.>,]>-<++++++[-<+[---------<+]->+[->+]-<]>+<-<+[-<+]>>+[-<[->++++++++++<]>>+]< takes input
>++++[->++++++++<]>.<+++++++[->++++++++++<]>+++.++++++++++.<+++++++++[->---------<]>--.[-]<< " is "
Line 1,016:
<[->+>+<<]>>>>>>>[-<<<<<->>>>>]<<<<<--
[>++++++++++[->+++++++++++<]>.+.+++++.>++++[->++++++++<]>.>] "not "
++++++++++[->+++++++++++<]>++.++.---------.++++.--------.>++++++++++. "prime" new line</
Will format as "# is/is not prime", naturally limited by cell size.
=={{header|Burlesque}}==
<
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:
<
1
blsq ) 12^^2\/?dr@.%{0==}ayn!
0
blsq ) 13^^2\/?dr@.%{0==}ayn!
1</
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}}==
<
{
unsigned int p;
Line 1,045:
if (!(n % p)) return 0;
return 1;
}</
=={{header|C sharp|C#}}==
<
{
if (n <= 1) return false;
Line 1,054:
if (n % i == 0) return false;
return true;
}</
=={{header|C++}}==
<
bool is_prime(unsigned int n)
Line 1,069:
return false;
return true;
}</
=={{header|Chapel}}==
{{trans|C++}}
<
{
if n == 2 then
Line 1,083:
return false;
return true;
}</
=={{header|Clojure}}==
The function used in both versions:
<
Testing divisors are in range from '''3''' to '''√{{overline| n }} ''' with step '''2''':
<
(or (= 2 x)
(and (< 1 x)
Line 1,096:
(not-any? (partial divides? x)
(range 3 (inc (Math/sqrt x)) 2)))))
</syntaxhighlight>
Testing only prime divisors:
<
(def primes (filter prime? (range)))
Line 1,108:
(not-any? (partial divides? x)
(take-while (partial >= (Math/sqrt x)) primes))))
</syntaxhighlight>
=={{header|CLU}}==
<
x0: int := s/2
if x0=0 then return(s) end
Line 1,138:
end
end
end start_up</
{{out}}
<pre>2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97</pre>
=={{header|CMake}}==
<
function(primep var n)
if(n GREATER 2)
Line 1,173:
set(${var} false PARENT_SCOPE) # n < 2 is not prime.
endif()
endfunction(primep)</
<
foreach(i -5 1 2 3 37 39)
primep(b ${i})
Line 1,183:
message(STATUS "${i} is _not_ prime.")
endif(b)
endforeach(i)</
=={{header|COBOL}}==
<
Program-Id. Primality-By-Subdiv.
Line 1,223:
Goback
.</
=={{header|CoffeeScript}}==
<
# 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</
=={{header|Common Lisp}}==
<
"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)))))</
===Alternate solution===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
<
(defun prime(n)
Line 1,260:
(format t "~d is not a prime number" n)))
(prime 7)
(prime 8)</
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
<
require "benchmark"
Line 1,392:
b.report("primep7?") { primep7?(p) }
puts
end</
{{out}}
<pre>p = 541
Line 1,422:
=={{header|D}}==
===Simple Version===
<
bool isPrime1(in int n) pure nothrow {
Line 1,438:
void main() {
iota(2, 40).filter!isPrime1.writeln;
}</
{{out}}
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
===Version with excluded multiplies of 2 and 3===
Same output.
<
// 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;
}</
===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.
<
bool isPrime3(T)(in T n) pure nothrow {
Line 1,486:
void main() {
iota(2, 40).filter!isPrime3.writeln;
}</
=={{header|Delphi}}==
=== First ===
<
var
I: Integer;
Line 1,507:
Break;
end;
end;</
=== Second ===
<
var
i: integer;
Line 1,524:
until i > Sqrt(x);
Result := True;
end;</
=={{header|E}}==
{{trans|D}}
<
if (n == 2) {
return true
Line 1,543:
return true
}
}</
=={{header|EchoLisp}}==
<
;; 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)</
=={{header|Eiffel}}==
<
APPLICATION
Line 1,631:
end
end</
<pre>False
True
Line 1,641:
=={{header|Elixir}}==
{{trans|Erlang}}
<
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</
{{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}}
<
(not (or (< a 2)
(cl-loop for x from 2 to (sqrt a)
when (zerop (% a x))
return t))))</
More concise, a little bit faster:
<
(and (> a 1)
(cl-loop for x from 2 to (sqrt a)
never (zerop (% a x)))))</
A little bit faster:
<
(and (> a 1)
(or (= a 2) (cl-oddp a))
(cl-loop for x from 3 to (sqrt a) by 2
never (zerop (% a x)))))</
More than 2 times faster, than the previous, doesn't use <tt>loop</tt> macro:
<
(not (or (< a 2)
(cl-some (lambda (x) (zerop (% a x))) (number-sequence 2 (sqrt a))))))</
Almost 2 times faster, than the previous:
<
(not (or (< a 2)
(and (/= a 2) (cl-evenp a))
(cl-some (lambda (x) (zerop (% a x))) (number-sequence 3 (sqrt a) 2)))))</
=={{header|Erlang}}==
<
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).</
=={{header|ERRE}}==
<
PROCEDURE ISPRIME(N%->OK%)
Line 1,717:
END FOR
END PROGRAM</
{{out}}
2 is prime
Line 1,746:
=={{header|Euphoria}}==
<
if n<=2 or remainder(n,2)=0 then
return 0
Line 1,757:
return 1
end if
end function</
=={{header|F Sharp|F#}}==
<
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</
{{out}}
> isPrime 1111111111111111111UL;;
Line 1,791:
and if you want to test really big numbers, use System.Numerics.BigInteger, but it's slower:
<
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</
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.
<
and IsPrime number =
Line 1,818:
false
else
IsPrimeCore number 0 number</
=={{header|Factor}}==
<
: prime? ( n -- ? )
Line 1,828:
{ [ dup even? ] [ 2 = ] }
[ 3 over sqrt 2 <range> [ mod 0 > ] with all? ]
} cond ;</
=={{header|FALSE}}==
<
3[\$@$@1+\$*>][\$@$@$@$@\/*=[%\~\$]?2+]#%
]?]?%]p:</
=={{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.
<
FUNCTION ISPRIME(n AS INTEGER) AS INTEGER
Line 1,875:
NEXT
PAUSE</
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Line 1,882:
=={{header|Forth}}==
<
dup 2 < if drop false
else dup 2 = if drop true
Line 1,892:
then 2 +
repeat 2drop true
then then then ;</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
LOGICAL :: isPrime
INTEGER, INTENT(IN) :: number
Line 1,914:
END DO
END IF
END FUNCTION</
=={{header|FreeBASIC}}==
<
Function isPrime(n As Integer) As Boolean
Line 1,939:
Print : Print
Print "Press any key to quit"
Sleep</
{{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!
<
{
for p = primes[]
Line 1,957:
return true
}</
=={{header|FunL}}==
<
def
Line 1,969:
| otherwise = (3..int(sqrt(n)) by 2).forall( (/|n) )
(10^10..10^10+50).filter( isPrime ).foreach( println )</
{{out}}
10000000019
Line 1,975:
=={{header|FutureBasic}}==
<
local fn isPrime( n as long ) as Boolean
Line 2,001:
next
HandleEvents</
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]'''
<
Public Sub Main()
Line 2,049:
Return bReturn
End</
Output:
<pre>1 is prime
Line 2,064:
=={{header|GAP}}==
<
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 ]</
=={{header|Go}}==
<
if n < 0 { n = -n }
switch {
Line 2,101:
}
return true
}</
Or, using recursion:
<
if n < 0 { n = -n }
if n <= 2 {
Line 2,118:
}
return true
}</
=={{header|Groovy}}==
<
it == 2 ||
it > 1 &&
Line 2,127:
}
(0..20).grep(isPrime)</
{{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:
<
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:
<
-- primeNums = filter (noDivsBy [2..]) [2..]
Line 2,142:
primeNums = 2 : 3 : filter (noDivsBy $ tail primeNums) [5,7..]
isPrime n = n > 1 && noDivsBy primeNums n</
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:
<
The following is an attempt at improving it, resulting in absolutely worst performing prime testing code I've ever seen, ever. A curious oddity.
<
=={{header|HicEst}}==
<
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</
=={{header|Icon}} and {{header|Unicon}}==
Procedure shown without a main program.
<
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</
=={{header|J}}==
{{eff note|J|1&p:}}
<
=={{header|Java}}==
<
if(a == 2){
return true;
Line 2,195:
}
return true;
}</
===By Regular Expression===
<
return !new String(new char[n]).matches(".?|(..+?)\\1+");
}</
=={{header|JavaScript}}==
<
if (n == 2 || n == 3 || n == 5 || n == 7) {
return true;
Line 2,214:
return true;
}
}</
=={{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.
<
1 < n || return false
n != 2 || return true
Line 2,266:
else
println("The function does not accurately calculate primes.")
end</
{{out}}
The primes <= 100 are:
Line 2,272:
=={{header|K}}==
<
&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</
=={{header|Kotlin}}==
<
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 ") }
}</
{{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}}
<
val .n = abs(.i)
if .n <= 2: return .n == 2
Line 2,310:
}
writeln where .isPrime, series 100</
=== Functional ===
Line 2,319:
{{works with|langur|0.8.1}}
<
.i > 2 and not any f(.x) .i div .x, pseries 2 to .i ^/ 2
writeln where .isPrime, series 100</
{{out}}
Line 2,328:
=={{header|Liberty BASIC}}==
<
print
[start]
Line 2,344:
next i
isPrime=1
end function</
{{out}}
<pre>Rosetta Code - Primality by trial division
Line 2,356:
=={{header|Lingo}}==
<
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</
<
repeat with i = 0 to 100
if isPrime(i) then primes.add(i)
end repeat
put primes</
{{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}}==
<
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</
=={{header|LSE64}}==
<
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</
=={{header|Lua}}==
<
if n <= 1 or ( n ~= 2 and n % 2 == 0 ) then
return false
Line 2,411:
return true
end</
Type of number Decimal.
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Inventory Known1=2@, 3@
IsPrime=lambda Known1 (x as decimal) -> {
Line 2,446:
Print
Print "Found ";count;" primes"
</syntaxhighlight>
=={{header|M4}}==
<
`ifelse(eval($2*$2>$1),1,
1,
Line 2,463:
isprime(9)
isprime(11)</
{{out}}
0
Line 2,470:
=={{header|Maple}}==
This could be coded in myriad ways; here is one.
<
if n <= 1 then
false
Line 2,485:
true
end if
end proc:</
Using this to pick off the primes up to 30, we get:
<
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]</
Here is a way to check that TrialDivision above agrees with Maple's built-in primality test (isprime).
<
true</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
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]]</
=={{header|MATLAB}}==
<
if n == 2
Line 2,519:
isPrime = all(mod(n, (3:round(sqrt(n))) ));
end</
{{out|Sample output}}
<
ans =
0 1 1 0 1 0 1 0 0 0 1 0 1 0</
=={{header|Maxima}}==
<
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] */</
=={{header|min}}==
{{works with|min|0.19.3}}
<
:n 3 :i n sqrt :m true :p
(i m <=) (
Line 2,551:
((true) (_prime?))
) case
) :prime?</
=={{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 С/П</
=={{header|MUMPS}}==
<
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</
Usage (0 is false, nonzero is true):
<pre>USER>W $$ISPRIME^ROSETTA(2)
Line 2,580:
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 2,645:
method isFalse public static returns boolean
return \isTrue</
{{out}}
<pre>$ java -cp . RCPrimality
Line 2,679:
===[[#REXX|Rexx]] version reimplemented in [[NetRexx]]===
{{trans|REXX}}
<
options replace format comments java crossref savelog symbols nobinary
Line 2,710:
end
return 1 /*I'm exhausted, it's prime!*/</
=={{header|newLISP}}==
Short-circuit evaluation ensures that the many Boolean expressions are calculated in the right order so as not to waste time.
<
(define (divisible? larger-number smaller-number)
Line 2,752:
(println (filter is-prime? (sequence 1 100)))
(exit)</
{{Output}}
Line 2,759:
=={{header|Nim}}==
Here are three ways to test primality using trial division.
<
proc prime(a: int): bool =
Line 2,778:
for i in 2..30:
echo i, " ", prime(i)</
{{out}}
Line 2,812:
=={{header|Objeck}}==
<
if(n <= 1) {
return false;
Line 2,824:
return true;
}</
=={{header|OCaml}}==
<
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</
=={{header|Octave}}==
This function works on vectors and matrix.
<
for r = 1:rows(n)
for c = 1:columns(n)
Line 2,863:
p = [1:100];
pv = isthisprime(p);
disp(p( pv ));</
=={{header|Oforth}}==
<
| 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 ;</
{{out}}
<pre>#isPrime 1000 seq filter println
Line 2,887:
=={{header|Ol}}==
<
(define (prime? number)
(define max (sqrt number))
Line 2,899:
(> (modulo number 2) 0)
(loop 3))))
</syntaxhighlight>
Testing:
<
; first prime numbers less than 100
(for-each (lambda (n)
Line 2,921:
12345676543211234567654321123456765432112345676543211234567654321123456765432112345676543211234567654321
))
</syntaxhighlight>
{{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}}==
<
local IPrime in
fun {IPrime N Acc}
Line 2,944:
else {IPrime N 2} end
end
end</
=={{header|Panda}}==
In Panda you write a boolean function by making it filter, either returning it's input or nothing.
<
p.gt(1) where q=p.sqrt NO(p.mod(2..q)==0)
1..100.prime</
=={{header|PARI/GP}}==
<
if(n < 4, return(n > 1)); /* Handle negatives */
forprime(p=2,sqrtint(n),
Line 2,960:
);
1
};</
=={{header|Pascal}}==
{{trans|BASIC}}
<
function prime(n: integer): boolean;
Line 2,992:
if (prime(n)) then
write(n, ' ');
end.</
{{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}}
<
{$IFDEF FPC}
{$MODE DELPHI}{$Smartlink ON}
Line 3,010:
write(actPrime,' ');
until nextPrime > 50;
end.</
;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:
<
$n % $_ or return for 2 .. sqrt $n;
$n > 1
}
print join(', ' => grep prime, 1..100), "\n";</
===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.
<
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";</
===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).
<
('1' x shift) !~ /^1?$|^(11+?)\1+$/
}
print join(', ', grep(isprime($_), 0..39)), "\n";</
=={{header|Phix}}==
<!--<
<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>
<!--</
{{out}}
<pre>
Line 3,069:
=={{header|PHP}}==
<
function prime($a) {
if (($a % 2 == 0 && $a != 2) || $a < 2)
Line 3,083:
if (prime($x)) echo "$x\n";
?></
===By Regular Expression===
<
function prime($a) {
return !preg_match('/^1?$|^(11+?)\1+$/', str_repeat('1', $a));
}
?></
=={{header|Picat}}==
Here are four different versions.
===Iterative===
<
if N == 2 then
true
Line 3,103:
N mod I > 0
end
end.</
===Recursive===
<
(N == 2 ; is_prime2b(N,3)).
Line 3,118:
;
is_prime2b(N,Div+2)
).</
===Functional===
<
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).</
===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.
<
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.</
===Test===
<
println([I : I in 1..100, is_prime1(I)]),
nl,
Line 3,150:
println([10**P,Primes.len])
end,
nl.</
Line 3,172:
=={{header|PicoLisp}}==
<
(or
(= N 2)
Line 3,181:
(for (D 3 T (+ D 2))
(T (> D S) T)
(T (=0 (% N D)) NIL) ) ) ) ) )</
=={{header|PL/I}}==
<
declare n fixed (15);
declare i fixed (10);
Line 3,196:
end;
return ('1'b);
end is_prime;</
=={{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.
<
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
Line 3,258:
CALL PR$NL;
EOF</
{{out}}
<pre>
Line 3,265:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function isPrime ($n) {
if ($n -eq 1) {$false}
Line 3,275:
}
}
1..15 | foreach{"isPrime $_ : $(isPrime $_)"}</
<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.
<
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 ).</
Example using SWI-Prolog:
<pre>?- time( (bagof( P, (prime(P), ((P > 100000, !, fail); true)), Bag),
Line 3,320:
=={{header|PureBasic}}==
<
Protected k
Line 3,338:
ProcedureReturn #True
EndProcedure</
=={{header|Python}}==
The simplest primality test, using trial division:
{{works with|Python|2.5}}
<
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))</
Another test. Exclude even numbers first:
<
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))</
Yet another test. Exclude multiples of 2 and 3, see http://www.devx.com/vb2themax/Tip/19051:
{{works with|Python|2.4}}
<
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</
===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]").
<
>>> 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]</
=={{header|Qi}}==
<
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))</
=={{header|Quackery}}==
Line 3,392:
<code>sqrt</code> is defined at [[Isqrt (integer square root) of X#Quackery]].
<
dup 1 & not iff [ drop false ] done
true swap dup sqrt
Line 3,400:
[ dip not conclude ] ]
drop ] is isprime ( n --> b )
</syntaxhighlight>
=={{header|R}}==
<
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</
=={{header|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)))))))</
=={{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"
$i > 1 and so $i %% none 2..$i.sqrt;
}</
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"
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;</
=={{header|REBOL}}==
<
case [
n = 2 [ true ]
Line 3,447:
]
]
]</
<
=={{header|REXX}}==
Line 3,462:
<br>function slowed up the function (for all three REXX versions), however, for larger numbers of '''N''', it would
<br>be faster.
<
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. */</
{{out|output|text= when using the default input of: <tt> 100 </tt>}}
<pre>
Line 3,516:
This version separates multiple-clause '''if''' statements, and also tests for low primes,
<br>making it about 8% faster.
<
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. */</
{{out|output|text= 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 '''do ... until ...''' was changed to '''do ... while ...'''.
<
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. */</
{{out|output|text= is identical to the first version when the same input is used.}}<br><br>
=={{header|Ring}}==
<
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</
=={{header|Ruby}}==
<
if a == 2
true
Line 3,620:
end
end
p (1..50).select{|i| prime(i)}</
The '''prime''' package in the stdlib for Ruby contains this compact <code>Prime#prime?</code> method:
<
def prime?(value, generator = Prime::Generator23.new)
return false if value < 2
Line 3,632:
end
end
p (1..50).select{|i| prime?(i)}</
Without any fancy stuff:
<
(enclose = lambda { |primes|
primes.last.succ.upto(limit) do |trial_pri|
Line 3,645:
}).call([2])
end
p primes(50)</
{{out}}
Line 3,651:
===By Regular Expression===
<
'1'*n !~ /^1?$|^(11+?)\1+$/
end</
===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
<
# the simplest PG primality test using the P3 prime generator
Line 3,762:
b.compare!
puts
end</
{{out}}
<pre>p = 541
Line 3,829:
=={{header|Run BASIC}}==
<
for i = 1 TO 50
if prime(i) <> 0 then print i;" ";
Line 3,843:
next i
[exit]
END FUNCTION</
2 3 5 7 11 13 17 19 23 25 29 31 37 41 43 47 49
=={{header|Rust}}==
<
match n {
0 | 1 => false,
Line 3,863:
println!("{} ", i);
}
}</
{{out}}
<pre>2 3 5 7 11 13 17 19 23 29 </pre>
=={{header|S-BASIC}}==
<syntaxhighlight lang="s-basic">
$lines
Line 3,902:
end
</syntaxhighlight>
{{out}}
<pre>
Line 3,909:
=={{header|S-lang}}==
<
{
if (n == 2) return(1);
Line 3,933:
print(strjoin(list_to_array(lst), ", "));
}
ptest();</
{{out}}
"2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61"
=={{header|SAS}}==
<
do n=1 to 1000;
link primep;
Line 3,958:
return;
keep n;
run;</
=={{header|Scala}}==
===Simple version===
<
n > 1 && (Iterator.from(2) takeWhile (d => d * d <= n) forall (n % _ != 0))</
===Accelerated version [[functional_programming|FP]] and parallel runabled===
// {{Out}}Best seen running in your browser [https://scastie.scala-lang.org/1RLimJrRQUqkXWkUwUxgYg Scastie (remote JVM)].
<
def isPrime(n: Long) =
n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) &&
Line 3,985:
println("All done")
}</
===Accelerated version [[functional_programming|FP]], tail recursion===
Tests 1.3 M numbers against OEIS prime numbers.
<
import scala.io.Source
Line 4,009:
for (i <- 0 to 1299709) assert(isPrime(i) == oeisPrimes.contains(i.toString), s"Wrong $i")
}</
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<
(define (*prime? divisor)
(or (> (* divisor divisor) number)
Line 4,019:
(*prime? (+ divisor 1)))))
(and (> number 1)
(*prime? 2)))</
<
(define (prime? n)
(if (< n 4) (> n 1)
Line 4,028:
(or (> (* k k) n)
(and (positive? (remainder n k))
(loop (+ k 2))))))))</
=={{header|Seed7}}==
<
result
var boolean: prime is FALSE;
Line 4,047:
prime := testNum > upTo;
end if;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/math.htm#is_prime]
=={{header|Sidef}}==
<
given (a) {
when (2) { true }
Line 4,057:
default { 3 .. a.isqrt -> any { .divides(a) } -> not }
}
}</
{{trans|Perl}}
Alternative version, excluding multiples of 2 and 3:
<
return (n >= 2) if (n < 4)
return false if (n%%2 || n%%3)
Line 4,067:
}
return true
}</
=={{header|Smalltalk}}==
<
isPrime := [:n |
n even ifTrue: [ ^n=2 ]
Line 4,079:
^true
]
]</
=={{header|SNOBOL4}}==
<
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</
===By Patterns===
Using the Abigail regex transated to Snobol patterns.
<
rprime str = dupl('1',n); rprime = n
pat1 = ('1' | '')
Line 4,104:
n = lt(n,50) n + 1 :s(loop)
output = rprimes
end</
{{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}}
<
set @number = 514229 -- number to check
Line 4,138:
' is prime'
end primalityTest
option (maxrecursion 0)</
=={{header|Standard ML}}==
<
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</
=={{header|Swift}}==
<
extension Int {
Line 4,169:
}
}
}</
=={{header|Tcl}}==
<
if {$n <= 1} {return false}
if {$n == 2} {return true}
Line 4,180:
}
return true
}</
=={{header|TI-83 BASIC}}==
Line 4,210:
=={{header|Tiny BASIC}}==
<
INPUT P
GOSUB 100
Line 4,226:
LET I = I + 1
IF I*I <= P THEN GOTO 110
RETURN</
=={{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()).</
=={{header|UNIX Shell}}==
Line 4,257:
{{works with|pdksh}}
{{works with|zsh}}
<
typeset n=$1 p=3
(( n == 2 )) && return 0 # 2 is prime.
Line 4,271:
done
return 0 # Yes, n is prime.
}</
{{works with|Bourne Shell}}
<
set -- "$1" 3
test "$1" -eq 2 && return 0 # 2 is prime.
Line 4,287:
done
return 0 # Yes, n is prime.
}</
=={{header|Ursala}}==
Excludes even numbers, and loops only up to the approximate square root or until a factor is found.
<
#import nat
prime = ~<{0,1}&& -={2,3}!| ~&h&& (all remainder)^Dtt/~& iota@K31</
Test program to try it on a few numbers:
<
test = prime* <5,6,7></
{{out}}
<true,false,true>
Line 4,304:
=={{header|V}}==
{{trans|Joy}}
<
2
[[dup * >] [true] [false] ifte [% 0 >] dip and]
[succ]
while
dup * <].</
{{out|Using it}}
<
=true
|4 prime?
=false</
=={{header|VBA}}==
<
Sub FirstTwentyPrimes()
Line 4,343:
IsPrime = True
End If
End Function</
{{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}}
<
If n = 2 Then
IsPrime = True
Line 4,369:
WScript.StdOut.Write n & " "
End If
Next</
{{out}}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Line 4,375:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<
var isPrime = Fn.new { |n|
Line 4,392:
for (test in tests) {
System.print("%(Fmt.d(2, test)) -> %(isPrime.call(test) ? "yes" : "no")")
}</
{{out}}
Line 4,407:
=={{header|XPL0}}==
<
int N;
int I;
Line 4,420:
Text(0, if Prime(Num) then "is " else "not ");
Text(0, "prime^M^J");
until Num = 0</
{{out}}
<pre>777777777
Line 4,431:
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<
if isPrime(i) print str$(i), " ";
next i
Line 4,446:
wend
return True
end sub</
=={{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
<
if(n.isEven or n<2) return(n==2);
(not [3..n.toFloat().sqrt().toInt(),2].filter1('wrap(m){n%m==0}))
}</
{{out}}
<pre>zkl: [1..].filter(20,isPrime)
|