Sequence of primes by trial division: Difference between revisions
Sequence of primes by trial division (view source)
Revision as of 13:49, 28 August 2022
, 1 year agosyntax highlighting fixup automation
SqrtNegInf (talk | contribs) m (→{{header|Perl}}: use true/false explicitly) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 1:
{{task|Prime Numbers}}
Line 32 ⟶ 30:
{{trans|Python}}
<
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))</
{{out}}
Line 46 ⟶ 44:
=={{header|Action!}}==
<
CARD i
Line 83 ⟶ 81:
PrintF("Primes in range [%U..%U]:%E",begin,end)
PrintPrimes(begin,end)
RETURN</
{{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).
<
procedure Sequence_Of_Primes is
Line 118 ⟶ 116:
end if;
end loop;
end Sequence_Of_Primes;</
{{out}}
Line 126 ⟶ 124:
=={{header|ALGOL 68}}==
Simple bounded sequence using the "is prime" routine from [[Primality by trial division#ALGOL 68]]
<
MODE ISPRIMEINT = INT;
PROC is prime = ( ISPRIMEINT p )BOOL:
Line 159 ⟶ 157:
print( ( " ", whole( primes[ p ], 0 ) ) )
OD;
print( ( newline ) )</
{{out}}
<pre>
Line 167 ⟶ 165:
=={{header|ALGOL W}}==
Uses the ALGOL W isPrime procedure from the Primality by Trial Division task.
<
% use the isPrime procedure from the Primality by Trial Division task %
logical procedure isPrime ( integer value n ) ; algol "isPrime" ;
Line 198 ⟶ 196:
end
end.</
{{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.
<
BEGIN
Line 260 ⟶ 258:
END
</syntaxhighlight>
{{out}}
Line 280 ⟶ 278:
=={{header|Arturo}}==
<
result: new [2]
loop range.step:2 3 upto 'x [
Line 294 ⟶ 292:
]
print getPrimes 100</
{{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">
``warps
%$ABCPR
Line 340 ⟶ 338:
//| \#0/ |
\{*}-------/
</syntaxhighlight>
{{out}}
Line 349 ⟶ 347:
=={{header|ATS}}==
<syntaxhighlight lang="ats">(*
// Lazy-evaluation:
// sieve for primes
Line 418 ⟶ 416:
end // end of [main0]
(* ****** ****** *)</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SEQUENCE_OF_PRIMES_BY_TRIAL_DIVISION.AWK
BEGIN {
Line 446 ⟶ 444:
return(1)
}
</syntaxhighlight>
{{out}}
<pre>
Line 454 ⟶ 452:
=={{header|BASIC256}}==
<
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</
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
=={{header|Batch File}}==
<syntaxhighlight lang="batch file">
@echo off
::Prime list using trial division
Line 515 ⟶ 513:
set lin=!cnt1:~-5!:
goto:eof
</syntaxhighlight>
{{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.
<
v_v#`\*:%*:*84\/*:*84::+<
v#>::48*:*/\48*:*%%!#v_1^
<^+1$_.#<5#<5#<+#<,#<<0:\</
{{out}}
Line 576 ⟶ 574:
=={{header|C}}==
<syntaxhighlight lang="c">
#include<stdio.h>
Line 611 ⟶ 609:
return 0;
}
</syntaxhighlight>
Output :
<pre>
Line 646 ⟶ 644:
=={{header|C sharp}}==
<
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);
}</
{{out}}
<pre>
Line 665 ⟶ 663:
=={{header|C++}}==
<
#include <math.h>
#include <iostream>
Line 696 ⟶ 694:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 707 ⟶ 705:
=={{header|Clojure}}==
<
(:require [clojure.math.numeric-tower :as math]))
Line 725 ⟶ 723:
a))
(println (primes-below 100))</
{{Output}}
Line 731 ⟶ 729:
=={{header|Common Lisp}}==
<
"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))</
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
<
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) }</
{{out}}
<pre>1000000007
Line 782 ⟶ 780:
{{trans|Haskell}}
This is a quite inefficient prime generator.
<
std.numeric, std.concurrency;
Line 804 ⟶ 802:
.take(20)
.writeln;
}</
{{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===
<
(define (is-prime? p)
(cond
Line 821 ⟶ 819:
(for/and ((d [3 5 .. (1+ (sqrt p))] )) (!zero? (modulo p d)))]))
(is-prime? 101) → #t </
===Bounded - List filter ===
<
→ (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)</
=== Unbounded - Sequence filter ===
<
→ # 👓 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)</
=== Unbounded - Stream ===
<
(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)</
=== Unbounded - Generator ===
<
(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)</
=== Unbounded - Background task ===
<
(lib 'bigint)
Line 879 ⟶ 877:
1000000000121
1000000000163
*stopped*</
=={{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.
<
[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>
{{out}}
<pre>
Line 1,071 ⟶ 1,069:
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,144 ⟶ 1,142:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,160 ⟶ 1,158:
=={{header|Elena}}==
ELENA 4.x :
<
import system'routines;
import system'math;
Line 1,173 ⟶ 1,171:
{
console.printLine(Primes(100))
}</
{{out}}
<pre>
Line 1,180 ⟶ 1,178:
=={{header|Elixir}}==
<
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)</
{{out}}
Line 1,202 ⟶ 1,200:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM PRIME_GENERATOR
Line 1,218 ⟶ 1,216:
END LOOP
END PROGRAM
</syntaxhighlight>
You must press Ctrl+Break to stop the program.
{{out}}
Line 1,241 ⟶ 1,239:
=={{header|F Sharp}}==
<
(*
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>
Let's print the sequence Prime[23] to Prime[42].
{{out}}
<
[23..42] |> Seq.iter(fun n->printf "%d " (Seq.item n SofE))
</syntaxhighlight>
<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}}==
<
math.ranges prettyprint sequences ;
Line 1,275 ⟶ 1,273:
! Show the first fifteen primes.
15 primes ltake list>array .</
{{out}}
<pre>
Line 1,282 ⟶ 1,280:
=={{header|FileMaker}}==
<
#May 10th., 2018.
Line 1,355 ⟶ 1,353:
End If
#
</syntaxhighlight>
=={{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">
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>
{{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">
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</
Start of output:
Line 1,498 ⟶ 1,496:
=={{header|FreeBASIC}}==
<
Function isPrime(n As Integer) As Boolean
Line 1,520 ⟶ 1,518:
Print : Print
Print "Press any key to quit"
Sleep</
{{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.
<
import "fmt"
Line 1,590 ⟶ 1,588:
}
fmt.Println()
}</
{{out}}
<pre>
Line 1,596 ⟶ 1,594:
</pre>
A simple iterative method, also unbounded and starting with 2.
<
import "fmt"
Line 1,627 ⟶ 1,625:
}
fmt.Println()
}</
{{out}}
<pre>
Line 1,635 ⟶ 1,633:
=={{header|Haskell}}==
The most basic:
<
With trial division emulated by additions (the seeds of Sieve):
<
With recursive filtering (in wrong order, from bigger to smaller natural numbers):
<
With iterated sieving (in right order, from smaller to bigger primes):
<
A proper [[Primality by trial division#Haskell|primality testing by trial division]] can be used to produce short ranges of primes more efficiently:
<
The standard optimal trial division version has <code>isPrime</code> in the above inlined:
<
primes = 2 : [n | n <- [3..], foldr (\p r-> p*p > n || rem n p > 0 && r)
True primes]</
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):
<
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)]</
It is also easy to extend the above in generating the factorization wheel automatically as follows:
<
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'</
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:
<
where
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]
-- map head
-- . iterate (\(p:xs) -> filter ((> 0).(`rem` p)) xs) $ [2..]</
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:
<
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]</
===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):
<
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..])</
<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):
<
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'</
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:
<
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</
<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:
<
try=. i.&.(p:inv) %: >./ y
candidate=. (y>1)*y=<.y
y #~ candidate*(y e.try) = +/ 0= try|/ y
)</
Example use:
<
1000003 1000033 1000037 1000039 1000081 1000099</
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}}
<
public class Test {
Line 1,805 ⟶ 1,803:
getPrimes(0, 100).forEach(p -> System.out.printf("%d, ", p));
}
}</
<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]].
<
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;</
'''Examples:'''
<syntaxhighlight lang
<
3
5
7</
Produce an array of primes, p, satisfying 50 <= p <= 99:
<syntaxhighlight lang
[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.
<
uplim::T
end
Line 1,853 ⟶ 1,851:
end
println("Primes ≤ 100: ", join((p for p in TDPrimes(100)), ", "))</
{{out}}
Line 1,859 ⟶ 1,857:
=={{header|Kotlin}}==
<
fun isPrime(n: Int): Boolean {
Line 1,885 ⟶ 1,883:
if (count % 15 == 0) println()
}
}</
{{out}}
Line 1,914 ⟶ 1,912:
=={{header|Lambdatalk}}==
<
{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>
More to see in [http://epsilonwiki.free.fr/lambdaway/?view=primes2]
=={{header|Liberty BASIC}}==
<syntaxhighlight 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>
{{out}}
<pre>
Line 1,986 ⟶ 1,984:
=={{header|Lua}}==
<
function isprime (x)
if x < 2 then return false end
Line 2,018 ⟶ 2,016:
-- Main procedure
show(primes(100))
show(primes(50, 150))</
{{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}}==
<
primeq[1]:=False
primeq[2]:=True
Line 2,030 ⟶ 2,028:
AllTrue[Range[2,Sqrt[n]+1],Mod[n,#]!=0&]
]
Select[Range[100],primeq]</
{{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}}==
<
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</
sieveOfEratosthenes(30)
Line 2,058 ⟶ 2,056:
=={{header|Nim}}==
{{trans|Kotlin}}
<
func isPrime(n: int): bool =
Line 2,080 ⟶ 2,078:
if count mod 15 == 0:
write(stdout, "\n")
echo()</
{{out}}
Line 2,111 ⟶ 2,109:
isPrime function is from Primality by trial division page
<
=={{header|PARI/GP}}==
<
if(n < 4, return(n > 1)); /* Handle negatives */
forprime(p=2,sqrt(n),
Line 2,122 ⟶ 2,120:
};
select(trial, [1..100])</
=={{header|Pascal}}==
{{libheader|primTrial}} {{works with|Free Pascal}}
Hiding the work in a existing unit.
<syntaxhighlight lang="pascal">
program PrimeRng;
uses
Line 2,139 ⟶ 2,137:
write(Range[i]:12);
writeln;
end.</
;output:
<pre> 1000000007 1000000009 1000000021 1000000033 1000000087 1000000093 1000000097</pre>
=={{header|Perl}}==
<
use enum <false true>;
Line 2,157 ⟶ 2,155:
say join ' ', grep { isprime $_ } 0 .. 100;
say join ' ', grep { isprime $_ } 12345678 .. 12345678+100;</
{{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]]
<!--<
<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>
<!--</
{{out}}
<pre>
Line 2,184 ⟶ 2,182:
=={{header|PicoLisp}}==
<
(or
(= N 2)
Line 2,198 ⟶ 2,196:
(filter prime? (range A B)) )
(println (primeseq 50 99))</
{{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">
(de comma_fmt (N) (format N 0 "." ","))
Line 2,247 ⟶ 2,245:
(prinl "The 10,001st prime is " (comma_fmt (primes T)))
(bye)
</syntaxhighlight>
{{Out}}
<pre>
Line 2,255 ⟶ 2,253:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function eratosthenes ($n) {
if($n -ge 1){
Line 2,278 ⟶ 2,276:
}
"$(sieve-start-end 100 200)"
</syntaxhighlight>
<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">
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>
{{Out}}
<pre>
Line 2,322 ⟶ 2,320:
=={{header|PureBasic}}==
<
#SPC=Chr(32)
#TB=~"\t"
Line 2,370 ⟶ 2,368:
Print(~"\nPrimes= "+Str(*count\i))
Input()
EndIf</
{{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">
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>
{{out}}
<pre>>>> primes_below(100)
Line 2,404 ⟶ 2,402:
===Fun With Lists===
<
primelist = []
def primer(n):
Line 2,420 ⟶ 2,418:
print(len(primelist))
print(primelist)</
{{out}}
Line 2,432 ⟶ 2,430:
Make a nest of primes less than n.
<
[ i^ isprime if
[ i^ join ] ] ] is primes< ( n --> [ )
100 primes< echo</
{{Out}}
Line 2,450 ⟶ 2,448:
This example uses infinite lists (streams) to implement a sieve algorithm that produces all prime numbers.
<
(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))</
==== 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.
<
(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))</
=== 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.
<
(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)</
=== Using generators ===
Line 2,499 ⟶ 2,497:
Yet another variation of the same algorithm as above, this time using generators.
<
(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)</
=={{header|Raku}}==
(formerly Perl 6)
Here is a straightforward implementation of the naive algorithm.
<syntaxhighlight lang="raku"
say @primes[^100];</
{{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: by using a negative number (for the program's argument), the list of primes is suppressed, but the prime count is still shown.
<
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. */</
{{out|output|text= when using the default input: <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 (the <big>'''//'''</big> tests, which is the ''remainder'' when doing 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. */</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} <br><br>
=={{header|Ring}}==
<
for i = 1 to 100
if isPrime(i) see "" + i + " " ok
Line 2,621 ⟶ 2,619:
next
return true
</syntaxhighlight>
=={{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:
<
pg = Prime::TrialDivisionGenerator.new
p pg.take(10) # => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
p pg.next # => 31</
===By Trial Division w/Prime Generator===
See https://rosettacode.org/wiki/Primality_by_trial_division#Ruby
<
# 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) }</
{{out}}
<pre>1000000007
Line 2,662 ⟶ 2,660:
=={{header|Rust}}==
<
fn is_prime(number: u32) -> bool {
#[allow(clippy::cast_precision_loss)]
Line 2,682 ⟶ 2,680:
);
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,690 ⟶ 2,688:
=={{header|S-BASIC}}==
<
comment
Prime number generator in S-BASIC. Only odd numbers are
Line 2,745 ⟶ 2,743:
print "All done. Goodbye"
end
</syntaxhighlight>
{{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'''.
<
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)</
{{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"]
<
var (counter, number) = (0, 0);
while (counter < amount) {
Line 2,780 ⟶ 2,778:
}
prime_seq(100, {|p| say p}); # prints the first 100 primes</
=={{header|Spin}}==
Line 2,788 ⟶ 2,786:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
Line 2,810 ⟶ 2,808:
waitcnt(_clkfreq + cnt)
ser.stop</
{{Out}}
<pre>
Line 2,817 ⟶ 2,815:
=={{header|Swift}}==
<
extension SequenceType {
Line 2,839 ⟶ 2,837:
}
return pastPrimes.last
}</
===Simple version===
{{works with|Swift 2 and Swift 3}}
<
func trialPrimes(_ max:Int){
Line 2,862 ⟶ 2,860:
trialPrimes(100)
print(primes)</
{{out}}
<pre>
Line 2,870 ⟶ 2,868:
=={{header|Tailspin}}==
Simplest version
<
templates ifPrime
def n: $;
Line 2,882 ⟶ 2,880:
100 -> primes -> '$;
' -> !OUT::write
</syntaxhighlight>
{{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.
<
proc havePrime n {
global primes
Line 2,905 ⟶ 2,903:
}
}
puts ""</
{{out}}
<pre>
Line 2,914 ⟶ 2,912:
{{libheader|Wren-fmt}}
Using a simple generator.
<
var primeSeq = Fiber.new {
Line 2,942 ⟶ 2,940:
if (count%15 == 0) System.print()
if (count == limit) break
}</
{{out}}
Line 2,970 ⟶ 2,968:
=={{header|XPL0}}==
<
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, ^ )]</
{{out}}
Line 2,992 ⟶ 2,990:
=={{header|Yabasic}}==
<
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</
{{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}}
<
(p>=2) and (not [2 .. p.toFloat().sqrt()].filter1('wrap(n){ p%n==0 }))
}
fcn primesBelow(n){ [0..n].filter(isPrime) }</
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.
<
{{out}}
<pre>
|