Sequence of primes by trial division: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Perl}}: use true/false explicitly)
m (syntax highlighting fixup automation)
Line 1:
 
 
{{task|Prime Numbers}}
 
Line 32 ⟶ 30:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F prime(a)
R !(a < 2 | any((2 .. Int(a ^ 0.5)).map(x -> @a % x == 0)))
 
Line 38 ⟶ 36:
R (0 .< n).filter(i -> prime(i))
 
print(primes_below(100))</langsyntaxhighlight>
 
{{out}}
Line 46 ⟶ 44:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC IsPrime(CARD a)
CARD i
 
Line 83 ⟶ 81:
PrintF("Primes in range [%U..%U]:%E",begin,end)
PrintPrimes(begin,end)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sequence_of_primes_by_trial_division.png Screenshot from Atari 8-bit computer]
Line 101 ⟶ 99:
Use the generic function Prime_Numbers.Is_Prime, as specified in [[Prime decomposition#Ada]]. The program reads two numbers A and B from the command line and prints all primes between A and B (inclusive).
 
<langsyntaxhighlight Adalang="ada">with Prime_Numbers, Ada.Text_IO, Ada.Command_Line;
 
procedure Sequence_Of_Primes is
Line 118 ⟶ 116:
end if;
end loop;
end Sequence_Of_Primes;</langsyntaxhighlight>
 
{{out}}
Line 126 ⟶ 124:
=={{header|ALGOL 68}}==
Simple bounded sequence using the "is prime" routine from [[Primality by trial division#ALGOL 68]]
<langsyntaxhighlight lang="algol68"># is prime PROC from the primality by trial division task #
MODE ISPRIMEINT = INT;
PROC is prime = ( ISPRIMEINT p )BOOL:
Line 159 ⟶ 157:
print( ( " ", whole( primes[ p ], 0 ) ) )
OD;
print( ( newline ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 167 ⟶ 165:
=={{header|ALGOL W}}==
Uses the ALGOL W isPrime procedure from the Primality by Trial Division task.
<langsyntaxhighlight lang="algolw">begin
% use the isPrime procedure from the Primality by Trial Division task %
logical procedure isPrime ( integer value n ) ; algol "isPrime" ;
Line 198 ⟶ 196:
end
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 210 ⟶ 208:
=={{header|ALGOL-M}}==
The approach here follows an example given by Edsger Dijkstra in his classic 1969 paper, Notes on Structured Programming. Only odd numbers above 2 are checked for primality, and only the prime numbers previously found (up to the square root of the number under examination) are tested as divisors.
<langsyntaxhighlight lang="algol">
BEGIN
 
Line 260 ⟶ 258:
 
END
</syntaxhighlight>
</lang>
 
{{out}}
Line 280 ⟶ 278:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">getPrimes: function [upto][
result: new [2]
loop range.step:2 3 upto 'x [
Line 294 ⟶ 292:
]
 
print getPrimes 100</langsyntaxhighlight>
 
{{out}}
Line 302 ⟶ 300:
=={{header|AsciiDots}}==
Program to generate all prime numbers up to the input (inclusive). This implementation is very inefficient currently since the primality test checks every number from 2 to N rather than checking up to the square root, excluding even numbers from the factor checks, etc.
<syntaxhighlight lang="asciidots">
<lang AsciiDots>
``warps
%$ABCPR
Line 340 ⟶ 338:
//| \#0/ |
\{*}-------/
</syntaxhighlight>
</lang>
 
{{out}}
Line 349 ⟶ 347:
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">(*
<lang ATS>(*
// Lazy-evaluation:
// sieve for primes
Line 418 ⟶ 416:
end // end of [main0]
 
(* ****** ****** *)</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SEQUENCE_OF_PRIMES_BY_TRIAL_DIVISION.AWK
BEGIN {
Line 446 ⟶ 444:
return(1)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 454 ⟶ 452:
 
=={{header|BASIC256}}==
<langsyntaxhighlight lang="freebasic">function isPrime(v)
if v < 2 then return False
if v mod 2 = 0 then return v = 2
Line 468 ⟶ 466:
if isPrime(i) then print string(i); " ";
next i
end</langsyntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
 
=={{header|Batch File}}==
<syntaxhighlight lang="batch file">
<lang Batch File>
@echo off
::Prime list using trial division
Line 515 ⟶ 513:
set lin=!cnt1:~-5!:
goto:eof
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 553 ⟶ 551:
Based on the test in the [[Primality_by_trial_division#Befunge|Primality by trial division]] task, this list all primes between 2 and 1,000,000.
 
<langsyntaxhighlight lang="befunge">2>:::"}"8*:*>`#@_48*:**2v
v_v#`\*:%*:*84\/*:*84::+<
v#>::48*:*/\48*:*%%!#v_1^
<^+1$_.#<5#<5#<+#<,#<<0:\</langsyntaxhighlight>
 
{{out}}
Line 576 ⟶ 574:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include<stdio.h>
 
Line 611 ⟶ 609:
return 0;
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 646 ⟶ 644:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 658 ⟶ 656:
static IEnumerable<int> Primes(int limit) => Enumerable.Range(2, limit-1).Where(IsPrime);
static bool IsPrime(int n) => Enumerable.Range(2, (int)Math.Sqrt(n)-1).All(i => n % i != 0);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 665 ⟶ 663:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <math.h>
#include <iostream>
Line 696 ⟶ 694:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 707 ⟶ 705:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(ns test-p.core
(:require [clojure.math.numeric-tower :as math]))
 
Line 725 ⟶ 723:
a))
 
(println (primes-below 100))</langsyntaxhighlight>
 
{{Output}}
Line 731 ⟶ 729:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun primes-up-to (max-number)
"Compute all primes up to MAX-NUMBER using trial division"
(loop for n from 2 upto max-number
Line 742 ⟶ 740:
(lambda (x) (integerp (/ n x))))
(print (primes-up-to 100))</langsyntaxhighlight>
 
Output: <pre>(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)</pre>
Line 748 ⟶ 746:
=={{header|Crystal}}==
See https://rosettacode.org/wiki/Primality_by_trial_division#Crystal
<langsyntaxhighlight lang="ruby">require "big"
 
def primep5?(n) # P5 Prime Generator primality test
Line 766 ⟶ 764:
 
# Create sequence of primes from 1_000_000_001 to 1_000_000_201
n = 1_000_000_001; n.step(to: n+200, by: 2) { |p| puts p if primep5?(p) }</langsyntaxhighlight>
{{out}}
<pre>1000000007
Line 782 ⟶ 780:
{{trans|Haskell}}
This is a quite inefficient prime generator.
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.algorithm, std.traits,
std.numeric, std.concurrency;
 
Line 804 ⟶ 802:
.take(20)
.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]</pre>
Line 813 ⟶ 811:
=={{header|EchoLisp}}==
===Trial division===
<langsyntaxhighlight lang="scheme">(lib 'sequences)
(define (is-prime? p)
(cond
Line 821 ⟶ 819:
(for/and ((d [3 5 .. (1+ (sqrt p))] )) (!zero? (modulo p d)))]))
 
(is-prime? 101) → #t </langsyntaxhighlight>
 
===Bounded - List filter ===
<langsyntaxhighlight lang="scheme">(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>
 
=== Unbounded - Sequence filter ===
<langsyntaxhighlight lang="scheme">(define f-primes (filter is-prime? [2 .. ]))
→ # 👓 filter: #sequence [2 3 .. Infinity[
 
(take f-primes 25)
→ (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>
 
=== Unbounded - Stream ===
<langsyntaxhighlight lang="scheme">(define (s-next-prime n) ;; n odd
(for ((p [n (+ n 2) .. ] ))
#:break (is-prime? p) => (cons p (+ p 2))))
Line 843 ⟶ 841:
 
(take s-primes 25)
→ (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>
 
=== Unbounded - Generator ===
<langsyntaxhighlight lang="scheme">(define (g-next-prime n)
(define next
(for ((p [n .. ] )) #:break (is-prime? p) => p ))
Line 855 ⟶ 853:
 
(take g-primes 25)
→ (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>
 
=== Unbounded - Background task ===
<langsyntaxhighlight lang="scheme">(lib 'tasks)
(lib 'bigint)
 
Line 879 ⟶ 877:
1000000000121
1000000000163
*stopped*</langsyntaxhighlight>
 
=={{header|EDSAC order code}}==
Line 887 ⟶ 885:
 
In the program as posted, the list of possible divisors holds 30 primes, from 5 to 131. The program finds primes less than 131^2 = 17161, the largest being 17159. Assuming 650 orders per second, this would have taken the original EDSAC about an hour.
<langsyntaxhighlight lang="edsac">
[List of primes by trial division, for Rosetta Code website.]
[EDSAC program, Initial Orders 2.]
Line 1,050 ⟶ 1,048:
E25Z [define entry point]
PF [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,071 ⟶ 1,069:
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,144 ⟶ 1,142:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,160 ⟶ 1,158:
=={{header|Elena}}==
ELENA 4.x :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
import system'math;
Line 1,173 ⟶ 1,171:
{
console.printLine(Primes(100))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,180 ⟶ 1,178:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Prime do
def sequence do
Stream.iterate(2, &(&1+1)) |> Stream.filter(&is_prime/1)
Line 1,194 ⟶ 1,192:
end
 
IO.inspect Prime.sequence |> Enum.take(20)</langsyntaxhighlight>
 
{{out}}
Line 1,202 ⟶ 1,200:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM PRIME_GENERATOR
 
Line 1,218 ⟶ 1,216:
END LOOP
END PROGRAM
</syntaxhighlight>
</lang>
You must press Ctrl+Break to stop the program.
{{out}}
Line 1,241 ⟶ 1,239:
 
=={{header|F Sharp}}==
<langsyntaxhighlight lang="fsharp">
(*
Nigel Galloway April 7th., 2017.
Line 1,250 ⟶ 1,248:
yield n; yield! fg (Seq.cache(Seq.filter (fun g->g%n<>0) (Seq.skip 1 ng)))}
fg (Seq.initInfinite(id)|>Seq.skip 2)
</syntaxhighlight>
</lang>
Let's print the sequence Prime[23] to Prime[42].
{{out}}
<langsyntaxhighlight lang="fsharp">
[23..42] |> Seq.iter(fun n->printf "%d " (Seq.item n SofE))
</syntaxhighlight>
</lang>
<pre>
89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191
Line 1,261 ⟶ 1,259:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators kernel lists lists.lazy math math.functions
math.ranges prettyprint sequences ;
 
Line 1,275 ⟶ 1,273:
 
! Show the first fifteen primes.
15 primes ltake list>array .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,282 ⟶ 1,280:
 
=={{header|FileMaker}}==
<langsyntaxhighlight lang="filemaker">
 
#May 10th., 2018.
Line 1,355 ⟶ 1,353:
End If
#
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
This program stores the generated primes into a user allocated array and uses the primes generated so far to test divisibility of subsequent candidates. In FORTH, the PAD can be used as a large memory area that is always available, and the main .primes word makes use of that.
<syntaxhighlight lang="forth">
<lang Forth>
variable p-start \ beginning of prime buffer
variable p-end \ end of prime buffer
Line 1,399 ⟶ 1,397:
i @ 5 .r
cell +loop ;
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,435 ⟶ 1,433:
This method avoids considering multiples of two and three, leading to the need to pre-load array PRIME and print the first few values explicitly rather than flounder about with special startup tricks. Even so, in order not to pre-load with 7, and to correctly start the factor testing with 5, the first few primes are found with some wasted effort because 5 is not needed at the start. Storing the primes as found has the obvious advantage of enabling divisions only by prime numbers, but care with the startup is needed to ensure that primes have indeed been stored before they are called for.
 
<syntaxhighlight lang="fortran">
<lang Fortran>
CONCOCTED BY R.N.MCLEAN, APPLIED MATHS COURSE, AUCKLAND UNIVERSITY, MCMLXXI.
INTEGER ENUFF,PRIME(44)
Line 1,480 ⟶ 1,478:
40 IF (N - 32767) 10,41,41
41 WRITE (6,34) (ALINE(I), I = 1,LL)
END</langsyntaxhighlight>
 
Start of output:
Line 1,498 ⟶ 1,496:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isPrime(n As Integer) As Boolean
Line 1,520 ⟶ 1,518:
Print : Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,536 ⟶ 1,534:
=={{header|Go}}==
An unbounded cascading filtering method using channels, adapted from the classic concurrent prime sieve example in the "Try Go" window at http://golang.org/, improved by postponing the initiation of the filtering by a prime until the prime's square is seen in the input.
<langsyntaxhighlight lang="go">package main
import "fmt"
Line 1,590 ⟶ 1,588:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,596 ⟶ 1,594:
</pre>
A simple iterative method, also unbounded and starting with 2.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,627 ⟶ 1,625:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,635 ⟶ 1,633:
=={{header|Haskell}}==
The most basic:
<langsyntaxhighlight lang="haskell">[n | n <- [2..], []==[i | i <- [2..n-1], rem n i == 0]]</langsyntaxhighlight>
 
With trial division emulated by additions (the seeds of Sieve):
<langsyntaxhighlight lang="haskell">[n | n <- [2..], []==[i | i <- [2..n-1], j <- [i,i+i..n], j==n]]</langsyntaxhighlight>
 
With recursive filtering (in wrong order, from bigger to smaller natural numbers):
<langsyntaxhighlight lang="haskell">foldr (\x r -> x : filter ((> 0).(`rem` x)) r) [] [2..]</langsyntaxhighlight>
 
With iterated sieving (in right order, from smaller to bigger primes):
<langsyntaxhighlight lang="haskell">Data.List.unfoldr (\(x:xs) -> Just (x, filter ((> 0).(`rem` x)) xs)) [2..]</langsyntaxhighlight>
 
A proper [[Primality by trial division#Haskell|primality testing by trial division]] can be used to produce short ranges of primes more efficiently:
<langsyntaxhighlight lang="haskell">primesFromTo n m = filter isPrime [n..m]</langsyntaxhighlight>
 
The standard optimal trial division version has <code>isPrime</code> in the above inlined:
 
<langsyntaxhighlight lang="haskell">-- primes = filter isPrime [2..]
primes = 2 : [n | n <- [3..], foldr (\p r-> p*p > n || rem n p > 0 && r)
True primes]</langsyntaxhighlight>
 
It is easy to amend this to test only odd numbers by only odd primes, or automatically skip the multiples of ''3'' (also, ''5'', etc.) by construction as well (a ''wheel factorization'' technique):
 
<langsyntaxhighlight lang="haskell">primes = 2 : 3 : [n | n <- [5,7..], foldr (\p r-> p*p > n || rem n p > 0 && r)
True (drop 1 primes)]
= [2,3,5] ++ [n | n <- scanl (+) 7 (cycle [4,2]),
foldr (\p r-> p*p > n || rem n p > 0 && r)
True (drop 2 primes)]
-- = [2,3,5,7] ++ [n | n <- scanl (+) 11 (cycle [2,4,2,4,6,2,6,4]), ... (drop 3 primes)]</langsyntaxhighlight>
 
It is also easy to extend the above in generating the factorization wheel automatically as follows:
 
<langsyntaxhighlight lang="haskell">-- autogenerates wheel primes, first sieve prime, and gaps
wheelGen :: Int -> ([Int],Int,[Int])
wheelGen n = loop 1 3 [2] [2] where
Line 1,691 ⟶ 1,689:
| any ((==) 0 . rem n)
(takeWhile ((<= n) . flip (^) 2) bps) = xtrprms (n + g) gs'
| otherwise = n : xtrprms (n + g) gs'</langsyntaxhighlight>
 
This is likely about the fastest of the trial division prime generators at just a few seconds to generate the primes up to ten million, which is about the limit of its practical range. An incremental Sieve of Eratosthenes sieve will extend the useful range about ten times this and isn't that much more complex.
Line 1,697 ⟶ 1,695:
===Sieve by trial division===
The classic David Turner's 1983 (1976? 1975?) SASL code repeatedly ''sieves'' a stream of candidate numbers from those divisible by a prime at a time, and works even for unbounded streams, thanks to lazy evaluation:
<langsyntaxhighlight lang="haskell">primesT = sieve [2..]
where
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]
-- map head
-- . iterate (\(p:xs) -> filter ((> 0).(`rem` p)) xs) $ [2..]</langsyntaxhighlight>
 
As shown in Melissa O'Neill's paper [http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf "The Genuine Sieve of Eratosthenes"], its complexity is quadratic in number of primes produced whereas that of optimal trial division is <math>O(n^{1.5}/(\log n)^{0.5})</math>, and of true SoE it is <math>O(n\log n\log\log n)</math>, in ''n'' primes produced.
Line 1,709 ⟶ 1,707:
===Bounded sieve by trial division===
Bounded formulation has normal trial division complexity, because it can stop early via an explicit guard:
<langsyntaxhighlight lang="haskell">primesTo m = sieve [2..m]
where
sieve (p:xs) | p*p > m = p : xs
| otherwise = p : sieve [x | x <- xs, rem x p /= 0]
-- (\(a,b:_) -> map head a ++ b) . span ((< m).(^2).head)
-- $ iterate (\(p:xs) -> filter ((>0).(`rem`p)) xs) [2..m]</langsyntaxhighlight>
 
===Postponed sieve by trial division===
{{trans|Racket}}
To make it unbounded, the guard cannot be simply discarded. The firing up of a filter by a prime should be ''postponed'' until its ''square'' is seen amongst the candidates (so a bigger chunk of input numbers are taken straight away as primes, between each opening up of a new filter, instead of just one head element in the non-postponed algorithm):
<langsyntaxhighlight lang="haskell">primesPT = sieve primesPT [2..]
where
sieve ~(p:ps) (x:xs) = x : after (p*p) xs
Line 1,726 ⟶ 1,724:
| otherwise = f (x:xs)
-- fix $ concatMap (fst.fst) . iterate (\((_,t),p:ps) ->
-- (span (< head ps^2) [x | x <- t, rem x p > 0], ps)) . (,) ([2,3],[4..])</langsyntaxhighlight>
 
<code>~(p:ps)</code> is a lazy pattern: the matching will be delayed until any of its variables are actually needed. Here it means that on the very first iteration the head of <code>primesPT</code> will be safely accessed only after it is already defined (by <code>x : after (p*p) ...</code>).
Line 1,732 ⟶ 1,730:
Note that the above introduced laziness for the evaluation of the head of the base primes list in order to avoid a race isn't necessary for the usual method of just introducing the first of the base primes before starting the computation as follows (use the same `wheelGen` as above for this wheel factorized version):
 
<langsyntaxhighlight lang="haskell">primesPTDW :: () -> [Int] -- nested filters, no matter how much postponed,
primesPTDW() = -- causes mucho allocation of deferred thunks!
wheelPrimes ++ _Y ((firstSievePrime :) . sieve cndts) where
Line 1,740 ⟶ 1,738:
q = bp * bp
after (x:xs') | x >= q = sieve (filter ((> 0) . (`rem` bp)) xs') bps'
| otherwise = x : after xs'</langsyntaxhighlight>
 
However, these postponed solutions are slower than the last of the basic trial division prime generators as the (nested) filters add greatly the the deferred "thunks" stored to the heap rather than the more direct (and more strict) determination of whether a number is prime as it's output.
Line 1,746 ⟶ 1,744:
===Segmented Generate and Test===
Explicating the run-time list of ''filters'' (created implicitly by the sieves above) as a list of ''factors to test by'' on each segment between the consecutive squares of primes (so that no testing is done prematurely), and rearranging to avoid recalculations, leads to the following:
<langsyntaxhighlight lang="haskell">import Data.List (inits)
 
primesST = 2 : 3 : sieve 5 9 (drop 2 primesST) (inits $ tail primesST)
where
sieve x q ps (fs:ft) = filter (\y-> all ((/=0).rem y) fs) [x,x+2..q-2]
++ sieve (q+2) (head ps^2) (tail ps) ft</langsyntaxhighlight>
<code>inits</code> makes a stream of (progressively growing) prefixes of an input stream, starting with an empty prefix, here making the <code>fs</code> parameter to get a sequence of values <code>[], [3], [3,5], ...</code>.
 
Line 1,762 ⟶ 1,760:
 
Implementation:
<langsyntaxhighlight Jlang="j">primTrial=:3 :0
try=. i.&.(p:inv) %: >./ y
candidate=. (y>1)*y=<.y
y #~ candidate*(y e.try) = +/ 0= try|/ y
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> primTrial 1e6+i.100
1000003 1000033 1000037 1000039 1000081 1000099</langsyntaxhighlight>
 
Note that this is a filter - it selects values from its argument which are prime. If no suitable values are found the resulting sequence of primes will be empty.
Line 1,781 ⟶ 1,779:
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.stream.IntStream;
 
public class Test {
Line 1,805 ⟶ 1,803:
getPrimes(0, 100).forEach(p -> System.out.printf("%d, ", p));
}
}</langsyntaxhighlight>
 
<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 1,813 ⟶ 1,811:
 
This entry uses is_prime/0 as defined at [[Primality_by_trial_division#jq]].
<langsyntaxhighlight lang="jq"># Produce a (possibly empty) stream of primes in the range [m,n], i.e. m <= p <= n
def primes(m; n):
([m,2] | max) as $m
Line 1,819 ⟶ 1,817:
elif $m == 2 then 2, primes(3;n)
else (1 + (2 * range($m/2 | floor; (n + 1) /2 | floor))) | select( is_prime )
end;</langsyntaxhighlight>
 
'''Examples:'''
<syntaxhighlight lang ="jq">primes(0;10)</langsyntaxhighlight>
<langsyntaxhighlight lang="sh">2
3
5
7</langsyntaxhighlight>
Produce an array of primes, p, satisfying 50 <= p <= 99:
<syntaxhighlight lang ="jq">[primes(50;99)]</langsyntaxhighlight>
[53,59,61,67,71,73,79,83,89,97]
 
Line 1,836 ⟶ 1,834:
I've chosen to solve this task by creating a new iterator type, <tt>TDPrimes</tt>. <tt>TDPrimes</tt> contains the upper limit of the sequence. The iteration state is the list of computed primes, and the item returned with each iteration is the current prime. The core of the solution is the <tt>next</tt> method for <tt>TDPrimes</tt>, which computes the next prime by trial division of the previously determined primes contained in the iteration state.
 
<langsyntaxhighlight lang="julia">struct TDPrimes{T<:Integer}
uplim::T
end
Line 1,853 ⟶ 1,851:
end
 
println("Primes ≤ 100: ", join((p for p in TDPrimes(100)), ", "))</langsyntaxhighlight>
 
{{out}}
Line 1,859 ⟶ 1,857:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun isPrime(n: Int): Boolean {
Line 1,885 ⟶ 1,883:
if (count % 15 == 0) println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,914 ⟶ 1,912:
=={{header|Lambdatalk}}==
 
<langsyntaxhighlight lang="scheme">
{def prime
{def prime.rec
Line 1,931 ⟶ 1,929:
{map prime {serie 9901 10000 2}}
-> 9901 9907 9923 9929 9931 9941 9949 9967 9973
</syntaxhighlight>
</lang>
More to see in [http://epsilonwiki.free.fr/lambdaway/?view=primes2]
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print "Rosetta Code - Sequence of primes by trial division"
print: print "Prime numbers between 1 and 50"
Line 1,956 ⟶ 1,954:
isPrime=1
end function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,986 ⟶ 1,984:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Returns true if x is prime, and false otherwise
function isprime (x)
if x < 2 then return false end
Line 2,018 ⟶ 2,016:
-- Main procedure
show(primes(100))
show(primes(50, 150))</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
Line 2,024 ⟶ 2,022:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[primeq]
primeq[1]:=False
primeq[2]:=True
Line 2,030 ⟶ 2,028:
AllTrue[Range[2,Sqrt[n]+1],Mod[n,#]!=0&]
]
Select[Range[100],primeq]</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|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function primeList = sieveOfEratosthenes(lastNumber)
 
list = (2:lastNumber); %Construct list of numbers
Line 2,049 ⟶ 2,047:
primeList = [primeList list]; %The rest of the numbers in the list are primes
end</langsyntaxhighlight>{{out|Sample Output}}
sieveOfEratosthenes(30)
Line 2,058 ⟶ 2,056:
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="nim">import strformat
 
func isPrime(n: int): bool =
Line 2,080 ⟶ 2,078:
if count mod 15 == 0:
write(stdout, "\n")
echo()</langsyntaxhighlight>
 
{{out}}
Line 2,111 ⟶ 2,109:
isPrime function is from Primality by trial division page
 
<langsyntaxhighlight Oforthlang="oforth">: primeSeq(n) n seq filter(#isPrime) ;</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">trial(n)={
if(n < 4, return(n > 1)); /* Handle negatives */
forprime(p=2,sqrt(n),
Line 2,122 ⟶ 2,120:
};
 
select(trial, [1..100])</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{libheader|primTrial}} {{works with|Free Pascal}}
Hiding the work in a existing unit.
<syntaxhighlight lang="pascal">
<lang Pascal>
program PrimeRng;
uses
Line 2,139 ⟶ 2,137:
write(Range[i]:12);
writeln;
end.</langsyntaxhighlight>
;output:
<pre> 1000000007 1000000009 1000000021 1000000033 1000000087 1000000093 1000000097</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use v5.36;
use enum <false true>;
 
Line 2,157 ⟶ 2,155:
 
say join ' ', grep { isprime $_ } 0 .. 100;
say join ' ', grep { isprime $_ } 12345678 .. 12345678+100;</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
Line 2,164 ⟶ 2,162:
=={{header|Phix}}==
Exact copy of [[Primality_by_trial_division#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 2,177 ⟶ 2,175:
<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 2,184 ⟶ 2,182:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de prime? (N)
(or
(= N 2)
Line 2,198 ⟶ 2,196:
(filter prime? (range A B)) )
 
(println (primeseq 50 99))</langsyntaxhighlight>
{{out}}
<pre>(53 59 61 67 71 73 79 83 89 97)</pre>
Line 2,206 ⟶ 2,204:
 
This is based on the wheel sieve Mark 1 in the paper, where candidates are taken from increasing size factorization wheels, where the next wheel of increasing size is used after the current wheel is completely "rolled."
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(de comma_fmt (N) (format N 0 "." ","))
 
Line 2,247 ⟶ 2,245:
(prinl "The 10,001st prime is " (comma_fmt (primes T)))
(bye)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,255 ⟶ 2,253:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function eratosthenes ($n) {
if($n -ge 1){
Line 2,278 ⟶ 2,276:
}
"$(sieve-start-end 100 200)"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,286 ⟶ 2,284:
=={{header|Prolog}}==
Creates a 2,3,5 factorization wheel to eliminate the majority of divisors and prime candidates before filtering.
<syntaxhighlight lang="prolog">
<lang Prolog>
wheel235(L) :-
W = [6, 4, 2, 4, 2, 4, 6, 2 | W],
Line 2,308 ⟶ 2,306:
roll235wheel(Limit, Candidates),
include(prime235, Candidates, Primes).
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,322 ⟶ 2,320:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
#SPC=Chr(32)
#TB=~"\t"
Line 2,370 ⟶ 2,368:
Print(~"\nPrimes= "+Str(*count\i))
Input()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Input (n1<n2 & n1>0)
Line 2,392 ⟶ 2,390:
=={{header|Python}}==
Using the basic ''prime()'' function from: [http://rosettacode.org/wiki/Primality_by_trial_division#Python "Primality by trial division"]
<syntaxhighlight lang="python">
<lang Python>
def prime(a):
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Line 2,398 ⟶ 2,396:
def primes_below(n):
return [i for i in range(n) if prime(i)]
</syntaxhighlight>
</lang>
{{out}}
<pre>>>> primes_below(100)
Line 2,404 ⟶ 2,402:
 
===Fun With Lists===
<langsyntaxhighlight lang="python">limiter = 100
primelist = []
def primer(n):
Line 2,420 ⟶ 2,418:
 
print(len(primelist))
print(primelist)</langsyntaxhighlight>
 
{{out}}
Line 2,432 ⟶ 2,430:
Make a nest of primes less than n.
 
<langsyntaxhighlight Quackerylang="quackery">[ [] swap times
[ i^ isprime if
[ i^ join ] ] ] is primes< ( n --> [ )
 
100 primes< echo</langsyntaxhighlight>
 
{{Out}}
Line 2,450 ⟶ 2,448:
This example uses infinite lists (streams) to implement a sieve algorithm that produces all prime numbers.
 
<langsyntaxhighlight Racketlang="racket">#lang lazy
(define nats (cons 1 (map add1 nats)))
(define (sift n l) (filter (λ(x) (not (zero? (modulo x n)))) l))
(define (sieve l) (cons (first l) (sieve (sift (first l) (rest l)))))
(define primes (sieve (rest nats)))
(!! (take 25 primes))</langsyntaxhighlight>
 
==== Optimized with postponed processing ====
Line 2,461 ⟶ 2,459:
Since a prime's multiples that count start from its square, we should only add them when we reach that square.
 
<langsyntaxhighlight Racketlang="racket">#lang lazy
(define nats (cons 1 (map add1 nats)))
(define (sift n l) (filter (λ(x) (not (zero? (modulo x n)))) l))
Line 2,470 ⟶ 2,468:
(λ(t) (sieve (sift (car ps) t) (cdr ps))))))
(define primes (sieve (cdr nats) primes))
(!! (take 25 primes))</langsyntaxhighlight>
 
=== Using threads and channels ===
Line 2,476 ⟶ 2,474:
Same algorithm as above, but now using threads and channels to produce a channel of all prime numbers (similar to newsqueak). The macro at the top is a convenient wrapper around definitions of channels using a thread that feeds them.
 
<langsyntaxhighlight Racketlang="racket">#lang racket
(define-syntax (define-thread-loop stx)
(syntax-case stx ()
Line 2,493 ⟶ 2,491:
(let ([x (channel-get c)]) (out! x) (set! c (sift x c))))
(define primes (let ([ns (nats)]) (channel-get ns) (sieve ns)))
(for/list ([i 25] [x (in-producer (λ() (channel-get primes)))]) x)</langsyntaxhighlight>
 
=== Using generators ===
Line 2,499 ⟶ 2,497:
Yet another variation of the same algorithm as above, this time using generators.
 
<langsyntaxhighlight Racketlang="racket">#lang racket
(require racket/generator)
(define nats (generator () (for ([i (in-naturals 1)]) (yield i))))
Line 2,508 ⟶ 2,506:
(generator () (let loop ([g g]) (let ([x (g)]) (yield x) (loop (sift x g))))))
(define primes (begin (nats) (sieve nats)))
(for/list ([i 25] [x (in-producer primes)]) x)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
Here is a straightforward implementation of the naive algorithm.
<syntaxhighlight lang="raku" perl6line>constant @primes = 2, 3, { first * %% none(@_), (@_[* - 1], * + 2 ... *) } ... *;
 
say @primes[^100];</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 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541</pre>
Line 2,525 ⟶ 2,523:
 
Usage note: &nbsp; by using a negative number (for the program's argument), the list of primes is suppressed, but the prime count is still shown.
<langsyntaxhighlight lang="rexx">/*REXX program lists a sequence of primes by testing primality by trial division. */
parse arg n . /*get optional number of primes to find*/
if n=='' | n=="," then n= 26 /*Not specified? Then use the default.*/
Line 2,542 ⟶ 2,540:
end /*j*/ /* [↑] only display N number of primes*/
/* [↓] display number of primes found.*/
say # ' primes found.' /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input: &nbsp; &nbsp; <tt> 26 </tt>}}
<pre>
Line 2,577 ⟶ 2,575:
This version shows how the REXX program may be optimized further by extending the list of low primes and
<br>the special low prime divisions &nbsp; (the &nbsp; <big>'''//'''</big> &nbsp; tests, &nbsp; which is the &nbsp; ''remainder'' &nbsp; when doing division).
<langsyntaxhighlight lang="rexx">/*REXX program lists a sequence of primes by testing primality by trial division. */
parse arg N . /*get optional number of primes to find*/
if N=='' | N=="," then N= 26 /*Not specified? Then assume default.*/
Line 2,603 ⟶ 2,601:
end /*j*/ /* [↑] only display N number of primes*/
/* [↓] display number of primes found.*/
say # ' primes found.' /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
for i = 1 to 100
if isPrime(i) see "" + i + " " ok
Line 2,621 ⟶ 2,619:
next
return true
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
The Prime class in the standard library has several Prime generators. In some methods it can be specified which generator will be used. The generator can be used on it's own:
<langsyntaxhighlight lang="ruby">require "prime"
 
pg = Prime::TrialDivisionGenerator.new
p pg.take(10) # => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
p pg.next # => 31</langsyntaxhighlight>
 
===By Trial Division w/Prime Generator===
See https://rosettacode.org/wiki/Primality_by_trial_division#Ruby
<langsyntaxhighlight lang="ruby">def primep5?(n) # P5 Prime Generator primality test
# P5 = 30*k + {7,11,13,17,19,23,29,31} # P5 primes candidates sequence
return [2, 3, 5].include?(n) if n < 7 # for small and negative values
Line 2,648 ⟶ 2,646:
 
# Create sequence of primes from 1_000_000_001 to 1_000_000_201
n = 1_000_000_001; n.step(n+200, 2) { |p| puts p if primep5?(p) }</langsyntaxhighlight>
{{out}}
<pre>1000000007
Line 2,662 ⟶ 2,660:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
fn is_prime(number: u32) -> bool {
#[allow(clippy::cast_precision_loss)]
Line 2,682 ⟶ 2,680:
);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,690 ⟶ 2,688:
 
=={{header|S-BASIC}}==
<langsyntaxhighlight lang="basic">
comment
Prime number generator in S-BASIC. Only odd numbers are
Line 2,745 ⟶ 2,743:
print "All done. Goodbye"
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,756 ⟶ 2,754:
===Odds-Only "infinite" primes generator using Streams and Co-Inductive Streams===
Using Streams, [http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf the "unfaithful sieve"], i.e. '''sub-optimal trial division sieve'''.
<langsyntaxhighlight lang="scala">def sieve(nums: Stream[Int]): Stream[Int] =
Stream.cons(nums.head, sieve((nums.tail).filter(_ % nums.head != 0)))
val primes = 2 #:: sieve(Stream.from(3, 2))
 
println(primes take 10 toList) // //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
println(primes takeWhile (_ < 30) toList) //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)</langsyntaxhighlight>
{{out}}Both println statements give the same results:
<pre>List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)</pre>
Line 2,769 ⟶ 2,767:
=={{header|Sidef}}==
Using the ''is_prime()'' function from: [http://rosettacode.org/wiki/Primality_by_trial_division#Sidef "Primality by trial division"]
<langsyntaxhighlight lang="ruby">func prime_seq(amount, callback) {
var (counter, number) = (0, 0);
while (counter < amount) {
Line 2,780 ⟶ 2,778:
}
 
prime_seq(100, {|p| say p}); # prints the first 100 primes</langsyntaxhighlight>
 
=={{header|Spin}}==
Line 2,788 ⟶ 2,786:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<langsyntaxhighlight lang="spin">con
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
Line 2,810 ⟶ 2,808:
 
waitcnt(_clkfreq + cnt)
ser.stop</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,817 ⟶ 2,815:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
 
extension SequenceType {
Line 2,839 ⟶ 2,837:
}
return pastPrimes.last
}</langsyntaxhighlight>
===Simple version===
{{works with|Swift 2 and Swift 3}}
<langsyntaxhighlight lang="swift">var primes = [2]
 
func trialPrimes(_ max:Int){
Line 2,862 ⟶ 2,860:
 
trialPrimes(100)
print(primes)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,870 ⟶ 2,868:
=={{header|Tailspin}}==
Simplest version
<langsyntaxhighlight lang="tailspin">
templates ifPrime
def n: $;
Line 2,882 ⟶ 2,880:
100 -> primes -> '$;
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,890 ⟶ 2,888:
=={{header|Tcl}}==
As we're generating a sequence of primes, we can use that sequence of primes to describe what we're filtering against.
<langsyntaxhighlight lang="tcl">set primes {}
proc havePrime n {
global primes
Line 2,905 ⟶ 2,903:
}
}
puts ""</langsyntaxhighlight>
{{out}}
<pre>
Line 2,914 ⟶ 2,912:
{{libheader|Wren-fmt}}
Using a simple generator.
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var primeSeq = Fiber.new {
Line 2,942 ⟶ 2,940:
if (count%15 == 0) System.print()
if (count == limit) break
}</langsyntaxhighlight>
 
{{out}}
Line 2,970 ⟶ 2,968:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
Line 2,984 ⟶ 2,982:
for N:= 2 to 100 do
if IsPrime(N) then
[IntOut(0, N); ChOut(0, ^ )]</langsyntaxhighlight>
 
{{out}}
Line 2,992 ⟶ 2,990:
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang="yabasic">sub isPrime(v)
if v < 2 then return False : fi
if mod(v, 2) = 0 then return v = 2 : fi
Line 3,006 ⟶ 3,004:
if isPrime(i) print str$(i), " ";
next i
end</langsyntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
Line 3,013 ⟶ 3,011:
The code in [[Extensible prime generator#zkl]] is a much better solution to this problem.
{{trans|Python}}
<langsyntaxhighlight lang="zkl">fcn isPrime(p){
(p>=2) and (not [2 .. p.toFloat().sqrt()].filter1('wrap(n){ p%n==0 }))
}
fcn primesBelow(n){ [0..n].filter(isPrime) }</langsyntaxhighlight>
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">primesBelow(100).toString(*).println();</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits