Extensible prime generator: Difference between revisions

m
Added Easylang
m (→‎{{header|REXX}}: added wording to the output text.)
m (Added Easylang)
 
(46 intermediate revisions by 21 users not shown)
Line 23:
'''Note 2:''' If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (2<sup>31</sup> or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).
 
'''Note 3:'''The task is written so it may be useful in solving the task &nbsp; [[Emirp primes]] &nbsp; as well as others (depending on its efficiency).
;nice site to check results:
Website with vast count of primes. Small ones for the first 10000 and up to 1,000,000,000,000 aka 1E12, divided in subranges : "Each compressed file contains 10 million primes" <br>
http://www.primos.mat.br/indexen.html
<br>
 
* The task is written so it may be useful in solving the task &nbsp; [[Emirp primes]] &nbsp; as well as others (depending on its efficiency).
<br>
<br>
;Reference:
* [http://www.primos.mat.br/indexen.html Prime Numbers]. Website with large count of primes.
 
<br><br>
 
=={{header|Ada}}==
Line 38:
The solution uses the package Miller_Rabin from the [[Miller-Rabin primality test]]. When using the gnat Ada compiler, the largest integer we can deal with is 2**63-1. For anything larger, we could use a big-num package.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Miller_Rabin;
 
procedure Prime_Gen is
Line 108:
"th prime:");
end;
end;</langsyntaxhighlight>
 
{{out}}
Line 120:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">SetBatchLines, -1
p := 1 ;p functions as the counter
Loop, 10000 {
Line 165:
return, 1
}
}</langsyntaxhighlight>
{{Output}}
<pre>First twenty primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
Line 171:
Number of primes between 7,700 and 8,000: 30
The 10,000th prime: 104729</pre>
 
=={{header|BASIC}}==
==={{header|FreeBASIC}}===
This program uses the Sieve Of Eratosthenes which is not very efficient for large primes but is quick enough for present purposes.
 
The size of the sieve array (of type Boolean) is calculated as 20 times the number of primes required which is big enough to compute
up to 50 million primes (a sieve size of 1 billion bytes) which takes under 50 seconds on my i3 @ 2.13 GHz. I've limited the
procedure to this but it should certainly be possible to use a much higher figure without running out of memory.
 
It would also be possible to use a more efficient algorithm to compute the optimal sieve size for smaller numbers of primes but this will suffice for now.
 
<syntaxhighlight lang="freebasic">' FB 1.05.0
 
Enum SieveLimitType
number
between
countBetween
End Enum
 
Sub printPrimes(low As Integer, high As Integer, slt As SieveLimitType)
If high < low OrElse low < 1 Then Return ' too small
If slt <> number AndAlso slt <> between AndAlso slt <> countBetween Then Return
If slt <> number AndAlso (low < 2 OrElse high < 2) Then Return
If slt <> number AndAlso high > 1000000000 Then Return ' too big
If slt = number AndAlso high > 50000000 Then Return ' too big
Dim As Integer n
If slt = number Then
n = 20 * high '' big enough to accomodate 50 million primes to which this procedure is limited
Else
n = high
End If
Dim a(2 To n) As Boolean '' only uses 1 byte per element
For i As Integer = 2 To n : a(i) = True : Next '' set all elements to True to start with
Dim As Integer p = 2, q
' mark non-prime numbers by setting the corresponding array element to False
 
Do
For j As Integer = p * p To n Step p
a(j) = False
Next j
' look for next True element in array after 'p'
q = 0
For j As Integer = p + 1 To Sqr(n)
If a(j) Then
q = j
Exit For
End If
Next j
If q = 0 Then Exit Do
p = q
Loop
 
Select Case As Const slt
Case number
Dim count As Integer = 0
For i As Integer = 2 To n
If a(i) Then
count += 1
If count >= low AndAlso count <= high Then
Print i; " ";
End If
If count = high Then Exit Select
End If
Next
 
Case between
For i As Integer = low To high
If a(i) Then
Print i; " ";
End if
Next
 
Case countBetween
Dim count As Integer = 0
For i As Integer = low To high
If a(i) Then count += 1
Next
Print count;
 
End Select
Print
End Sub
 
Print "The first 20 primes are :"
Print
printPrimes(1, 20, number)
Print
Print "The primes between 100 and 150 are :"
Print
printPrimes(100, 150, between)
Print
Print "The number of primes between 7700 and 8000 is :";
printPrimes(7700, 8000, countBetween)
Print
Print "The 10000th prime is :";
Dim t As Double = timer
printPrimes(10000, 10000, number)
Print "Computed in "; CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "The 1000000th prime is :";
t = timer
printPrimes(1000000, 1000000, number)
Print "Computed in ";CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "The 50000000th prime is :";
t = timer
printPrimes(50000000, 50000000, number)
Print "Computed in ";CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
The first 20 primes are :
 
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
 
The primes between 100 and 150 are :
 
101 103 107 109 113 127 131 137 139 149
 
The number of primes between 7700 and 8000 is : 30
 
The 10000th prime is : 104729
Computed in 8 ms
 
The 1000000th prime is : 15485863
Computed in 775 ms
 
The 50000000th prime is : 982451653
Computed in 46703 ms
</pre>
 
=={{header|BQN}}==
This implementation uses a simple segmented sieve similar to the one in [[Sieve of Eratosthenes#BQN|Sieve of Eratosthenes]]. In order to match the task most closely, it returns a generator function (implemented as a closure) that outputs another prime on each call, using an underlying <code>primes</code> array that's extended as necessary. Working with one prime at a time is inefficient in an array language, and the given tasks can be solved more quickly using functions from bqn-libs [https://github.com/mlochbaum/bqn-libs/blob/master/primes.bqn primes.bqn], which also uses a more complicated and faster underlying sieve.
<syntaxhighlight lang="bqn"># Function that returns a new prime generator
PrimeGen ← {𝕤
i ← 0 # Counter: index of next prime to be output
primes ← ↕0
next ← 2
Sieve ← { p 𝕊 i‿n:
E ← {↕∘⌈⌾(((𝕩|-i)+𝕩×⊢)⁼)n-i} # Indices of multiples of 𝕩
i + / (1⥊˜n-i) E⊸{0¨⌾(𝕨⊸⊏)𝕩}´ p # Primes in segment [i,n)
}
{𝕤
{ i=≠primes ? # Extend if required
next ↩ ((2⋆24)⊸+ ⌊ ט) old←next # Sieve at most 16M new entries
primes ∾↩ (primes(⍋↑⊣)√next) Sieve old‿next
;@}
(i+↩1) ⊢ i⊑primes
}
}
_w_←{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} # Looping utility for the session below</syntaxhighlight>
{{out}}
<syntaxhighlight lang="bqn"> pg ← PrimeGen@
(function block)
 
PG¨ ↕20
⟨ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 ⟩
 
{p←↕0 ⋄ PG∘{ p∾↩𝕩}_w_(<⟜ 150) PG _w_(<⟜ 100)0 ⋄ p}
⟨ 101 103 107 109 113 127 131 137 139 149 ⟩
 
{p←0 ⋄ PG∘{𝕤⋄p+↩1}_w_(<⟜8000) PG _w_(<⟜7700)0 ⋄ p}
30
 
(PrimeGen@)⍟1e4 @ # Reset the count with a new generator
104729</syntaxhighlight>
 
=={{header|C}}==
Extends the list of primes by sieving more chunks of integers. There's no serious optimizations. The code can calculate all 32-bit primes in some seconds, and will overflow beyond that.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 271 ⟶ 440:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 292 ⟶ 461:
* ~100,000,000 primes is about the limits of this algorithm. This version is not as idiomatic to C as a page-segmented sieve would be.
 
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdlib.h>
Line 416 ⟶ 585:
return 0;
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 431 ⟶ 600:
Based on "The Genuine Sieve of Eratosthenes" by Melissa E. O'Neill.
UPDATE: Added wheel optimization to match its C counterpart.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cstdint>
#include <queue>
Line 554 ⟶ 723:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 572 ⟶ 741:
This is a "segmented sieve" implementation inspired by the original C solution.
Execution time is about 4 seconds on my system (macOS 10.15.4, 3.2GHz Quad-Core Intel Core i5).
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <cmath>
Line 697 ⟶ 866:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 715 ⟶ 884:
=={{header|Clojure}}==
 
<langsyntaxhighlight Clojurelang="clojure">ns test-project-intellij.core
(:gen-class)
(:require [clojure.string :as string]))
Line 764 ⟶ 933:
 
 
}</langsyntaxhighlight>
{{out}}
<pre>
Line 776 ⟶ 945:
 
The above version is adequate for ranges up to the low millions, so covers the task requirements of primes up to just over a hundred thousands easily. However, it has a O(n^(3/2)) performance which means that it gets slow quite quickly with range as compared to a true incremental Sieve of Eratosthenes, which has O(n (log n)) performance. The following code is about the same speed for ranges in the low millions but quickly passes the above code in speed for large ranges to where it only takes 10's of seconds for a range of a hundred million where the above code takes thousands of seconds. The code is based on the Richard Bird list based Sieve of Eratosthenes mentioned in the O'Neil article but has infinite tree folding added as well as wheel factorization so that it is about the same speed and performance as a Sieve of Eratosthenes based on a priority queue; the code is written here in purely functional form with no mutation, as follows:
<langsyntaxhighlight lang="clojure">(deftype CIS [v cont]
clojure.lang.ISeq
(first [_] v)
Line 873 ⟶ 1,042:
(if (<= i 0)
(->CIS (get wheel-primes 0) ff)
(recur (- i 1) (fn [] (->CIS (get wheel-primes i) ff)))))))</langsyntaxhighlight>
 
Now these functional incremental sieves are of limited use if one requires ranges of billions as they are hundreds of times slower than a version of a bit-packed page-segmented mutable array Sieve of Eratosthenes, which for Clojure there is a version at the end of Clojure [[Sieve_of_Eratosthenes#Unbounded_Versions]] section on the Sieve of Eratosthenes task page; this version will handle ranges of a billion in seconds rather than hundreds of seconds.
 
=={{header|CoffeeScript}}==
This uses the prime number generation algorithm outlined in the paper, "Two Compact Incremental Prime Sieves" by Jonathon P. Sorenson. This algorithm is essentially a rolling segmented SoE, and is quite fast for languages that have good array processing.
<syntaxhighlight lang="coffeescript">
primes = () ->
yield 2
yield 3
 
sieve = ([] for i in [1..3])
sieve[0].push 3
[r, s] = [3, 9]
pos = 1
n = 5
loop
isPrime = true
if sieve[pos].length > 0 # this entry has a list of factors
isPrime = false
sieve[(pos + m) % sieve.length].push m for m in sieve[pos]
sieve[pos] = []
 
if n is s # n is the next square
if isPrime
isPrime = false # r divides n, so not actually prime
sieve[(pos + r) % sieve.length].push r # however, r is prime
r += 2
s = r*r
 
yield n if isPrime
n += 2
pos += 1
if pos is sieve.length
sieve.push [] # array size must exceed largest prime found
sieve.push [] # adding two entries keeps size = O(sqrt n)
pos = 0
 
undefined # prevent CoffeeScript from aggregating values
 
module.exports = {
primes
}
</syntaxhighlight>
Driver code:
<syntaxhighlight lang="coffeescript">
primes = require('sieve').primes
 
gen = primes()
console.log "The first 20 primes: #{gen.next().value for _ in [1..20]}"
 
p100_150 = (while (p = gen.next().value) < 150 then p).filter (n) -> n > 100
console.log "The primes between 100 and 150: #{p100_150}"
 
while gen.next().value < 7700
undefined
count = 1
while gen.next().value < 8000
++count
 
console.log "There are #{count} primes between 7,700 and 8,000."
 
n = 10
c = 0
gen = primes()
loop
p = gen.next().value
c += 1
if c is n
console.log "The #{n}th prime is #{p}"
break if n is 10_000_000
n *= 10
</syntaxhighlight>
{{Out}}
<pre>
The first 20 primes: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71
The primes between 100 and 150: 101,103,107,109,113,127,131,137,139,149
There are 30 primes between 7,700 and 8,000.
The 10th prime is 29
The 100th prime is 541
The 1000th prime is 7919
The 10000th prime is 104729
The 100000th prime is 1299709
The 1000000th prime is 15485863
</pre>
=={{header|D}}==
This uses a Prime struct defined in the [[Sieve of Eratosthenes#Extensible Version|third entry of the Sieve of Eratosthenes]] task. Prime keeps and extends a dynamic array instance member of uints. The Prime struct has a opCall that returns the n-th prime number. The opCall calls a grow() private method until the dynamic array of primes is long enough to contain the required answer. The function grow() just grows the dynamic array geometrically and performs a normal sieving. On a 64 bit system this program works up to the maximum prime number that can be represented in the 32 bits of an uint. This program is less efficient than the C entry, so it's better to not use it past some tens of millions of primes, but it's enough for more limited usages.
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.range, std.algorithm, sieve_of_eratosthenes3;
 
Line 890 ⟶ 1,140:
.filter!q{a > 7_699}.walkLength);
writeln("10,000th prime: ", prime(9_999));
}</langsyntaxhighlight>
{{out}}
<pre>First twenty primes:
Line 900 ⟶ 1,150:
 
===Faster Alternative Version===
<langsyntaxhighlight lang="d">/// Prime sieve based on: http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf
 
import std.container: Array, BinaryHeap, RedBlackTree;
Line 1,010 ⟶ 1,260:
LazyPrimeSieve().until!q{a > 8_000}.filter!q{a > 7_699}.walkLength);
writeln("10,000th prime: ", LazyPrimeSieve().dropExactly(9999).front);
}</langsyntaxhighlight>
{{out}}
<pre>Sum of first 100,000 primes: 62260698721
Line 1,024 ⟶ 1,274:
A version based on a (hashed) Map:
 
<langsyntaxhighlight lang="dart">Iterable<int> primesMap() {
Iterable<int> oddprms() sync* {
yield(3); yield(5); // need at least 2 for initialization
Line 1,073 ⟶ 1,323:
final answer = primesMap().takeWhile((p)=>p<2000000).reduce((a,p)=>a+p);
final elapsed = DateTime.now().millisecondsSinceEpoch - start;
}</langsyntaxhighlight>
{{output}}
<pre>The first 20 primes:
Line 1,093 ⟶ 1,343:
 
It solves the Euler Problem 10 in almost too short a time to be measured, and it becomes useful for ranges of hundreds of thousands. It can count all the primes to a billion on the low end tablet CPU of an Intel x5-Z8350 at 1.92 Gigahertz used to develop this in 40 seconds but using a generator slows the performance and it can use the provided `countPrimesTo` function to do the job four times as fast by directly manipulating the provided iteration of sieved bit-packed arrays.
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
This prime generator is based on a custom Delphi object. The object has a number of features:
 
1. It sieves primes generating an array of flags that tells whether a number is prime or not.
 
2. Using that table it generates another table of just prime numbers.
 
3. The tables can be up 4 billion flags under a 32-bit operating system. However there is also the option to use "Bit-Booleans" which can push the limit up to 32
 
4. Tables are generated fast; 1 million primes takes 9 miliseconds to generate; 100 million primes requires about 2 seconds.
 
5. The tool can be used from just about any prime based task. You can determine if a number is prime by testing the corresponding flag. You can find the nth prime by looking at the nth entry int he prime table. You can count primes between two values by counting flags.
 
 
 
<syntaxhighlight lang="Delphi">
 
{{-------- Declaration for BitBoolean Array ------------------}
 
{Bit boolean - because it stores 8 bools per bytye, it will}
{handle up to 16 gigabyte in a 32 bit programming environment}
 
type TBitBoolArray = class(TObject)
private
FSize: int64;
ByteArray: array of Byte;
function GetValue(Index: int64): boolean;
procedure WriteValue(Index: int64; const Value: boolean);
function GetSize: int64;
procedure SetSize(const Value: int64);
protected
public
property Value[Index: int64]: boolean read GetValue write WriteValue; default;
constructor Create;
property Count: int64 read GetSize write SetSize;
procedure Clear(Value: boolean);
end;
 
 
{------------------------------------------------------------}
{ Implementation for Bitboolean array -----------------------}
{------------------------------------------------------------}
 
{ TBitBoolArray }
 
const BitArray: array [0..7] of byte = ($01, $02, $04, $08, $10, $20, $40, $80);
 
function TBitBoolArray.GetValue(Index: int64): boolean;
begin
{Note: (Index and 7) is faster than (Index mod 8)}
Result:=(ByteArray[Index shr 3] and BitArray[Index and 7])<>0;
end;
 
 
procedure TBitBoolArray.WriteValue(Index: int64; const Value: boolean);
var Inx: int64;
begin
Inx:=Index shr 3;
{Note: (Index and 7) is faster than (Index mod 8)}
if Value then ByteArray[Inx]:=ByteArray[Inx] or BitArray[Index and 7]
else ByteArray[Inx]:=ByteArray[Inx] and not BitArray[Index and 7]
end;
 
 
constructor TBitBoolArray.Create;
begin
SetLength(ByteArray,0);
end;
 
 
function TBitBoolArray.GetSize: int64;
begin
Result:=FSize;
end;
 
 
procedure TBitBoolArray.SetSize(const Value: int64);
var Len: int64;
begin
FSize:=Value;
{Storing 8 items per byte}
Len:=Value div 8;
{We need one more to fill partial bits}
if (Value mod 8)<>0 then Inc(Len);
SetLength(ByteArray,Len);
end;
 
 
procedure TBitBoolArray.Clear(Value: boolean);
var Fill: byte;
begin
if Value then Fill:=$FF else Fill:=0;
FillChar(ByteArray[0],Length(ByteArray),Fill);
end;
 
 
 
 
{========== TPrimeSieve =======================================================}
 
 
{Sieve object the generates and holds prime values}
 
{Enable this flag if you need primes past 2 billion.
The flag signals the code to use bit-booleans arrays
which can contain up to 8 x 4 gigabytes = 32 gig booleans.}
 
// {$define BITBOOL}
 
type TPrimeSieve = class(TObject)
private
{$ifdef BITBOOL}
PrimeArray: TBitBoolArray;
{$else}
PrimeArray: array of boolean;
{$endif}
FArraySize: int64;
FPrimeCount: int64;
function GetPrime(Index: int64): boolean;
procedure Clear;
function GetCount: int64;
procedure BuildPrimeTable;
protected
procedure DoSieve;
property ArraySize: int64 read FArraySize;
public
Primes: TIntegerDynArray;
BitBoolean: boolean;
constructor Create;
destructor Destroy; override;
procedure Intialize(Size: int64);
property Flags[Index: int64]: boolean read GetPrime; default;
function NextPrime(Start: int64): int64;
function PreviousPrime(Start: int64): int64;
property Count: int64 read GetCount;
property PrimeCount: int64 read FPrimeCount;
end;
 
 
 
 
 
 
procedure TPrimeSieve.Clear;
begin
{$ifdef BITBOOL}
PrimeArray.Clear(True);
{$else}
FillChar(PrimeArray[0],Length(PrimeArray),True);
{$endif}
end;
 
 
 
constructor TPrimeSieve.Create;
begin
{$ifdef BITBOOL}
PrimeArray:=TBitBoolArray.Create;
BitBoolean:=True;
{$else}
BitBoolean:=False;
{$endif}
end;
 
 
destructor TPrimeSieve.Destroy;
begin
{$ifdef BITBOOL}
PrimeArray.Free;
{$endif}
inherited;
end;
 
 
 
procedure TPrimeSieve.BuildPrimeTable;
{This builds a table of primes which is}
{easier to use than a table of flags}
var I,Inx: integer;
begin
SetLength(Primes,Self.PrimeCount);
Inx:=0;
for I:=0 to Self.Count-1 do
if Flags[I] then
begin
Primes[Inx]:=I;
Inc(Inx);
end;
end;
 
 
 
procedure TPrimeSieve.DoSieve;
{Load flags with true/false to flag that number is prime}
{Note: does not store even values, because except for 2, all primes are even}
{Starts storing flags at Index=3, so reading/writing routines compensate}
{Uses for-loops for boolean arrays and while-loops for Bit-Booleans arrays}
{$ifdef BITBOOL}
var Offset, I, K: int64;
{$else}
var Offset, I, K: cardinal;
{$endif}
begin
Clear;
{Compensate from primes 1,2 & 3, which aren't stored}
FPrimeCount:=ArraySize+3;
{$ifdef BITBOOL}
I:=0;
while I<ArraySize do
{$else}
for I:=0 to ArraySize-1 do
{$endif}
begin
if PrimeArray[I] then
begin
Offset:= I + I + 3;
K:= I + Offset;
while K <=(ArraySize-1) do
begin
if PrimeArray[K] then Dec(FPrimeCount);
PrimeArray[K]:= False;
K:= K + Offset;
end;
end;
{$ifdef BITBOOL} Inc(I); {$endif}
end;
BuildPrimeTable;
end;
 
 
 
function TPrimeSieve.GetPrime(Index: int64): boolean;
{Get a prime flag from array - compensates}
{ for 0,1,2 and even numbers not being stored}
begin
if Index = 1 then Result:=False
else if Index = 2 then Result:=True
else if (Index and 1)=0 then Result:=false
else Result:=PrimeArray[(Index div 2)-1];
end;
 
 
function TPrimeSieve.NextPrime(Start: int64): int64;
{Get next prime after Start}
begin
Result:=Start+1;
while Result<=((ArraySize-1) * 2) do
begin
if Self.Flags[Result] then break;
Inc(Result);
end;
end;
 
 
 
function TPrimeSieve.PreviousPrime(Start: int64): int64;
{Get Previous prime Before Start}
begin
Result:=Start-1;
while Result>0 do
begin
if Self.Flags[Result] then break;
Dec(Result);
end;
end;
 
 
procedure TPrimeSieve.Intialize(Size: int64);
{Set array size and do Sieve to load flag array with}
begin
FArraySize:=Size div 2;
{$ifdef BITBOOL}
PrimeArray.Count:=FArraySize;
{$else}
SetLength(PrimeArray,FArraySize);
{$endif}
DoSieve;
end;
 
 
 
function TPrimeSieve.GetCount: int64;
begin
Result:=FArraySize * 2;
end;
 
 
{===========================================================}
 
procedure ExtensiblePrimeGenerator(Memo: TMemo);
var I,Cnt: integer;
var Sieve: TPrimeSieve;
var S: string;
begin
Sieve:=TPrimeSieve.Create;
try
{Build a table with 1-million primes}
Sieve.Intialize(1000000);
 
Memo.Lines.Add('Showing the first twenty primes');
S:='';
for I:=0 to 20-1 do
S:=S+' '+IntToStr(Sieve.Primes[I]);
Memo.Lines.Add(S);
Memo.Lines.Add('');
 
Memo.Lines.Add('Showing the primes between 100 and 150.');
S:='';
for I:=100 to 150 do
if Sieve.Flags[I] then S:=S+' '+IntToStr(I);
Memo.Lines.Add(S);
Memo.Lines.Add('');
 
Memo.Lines.Add('Showing the number of primes between 7,700 and 8,000.');
Cnt:=0;
for I:=7700 to 8000 do
if Sieve.Flags[I] then Inc(Cnt);
Memo.Lines.Add('Count = '+IntToStr(Cnt));
Memo.Lines.Add('');
 
Memo.Lines.Add('Showing the 10,000th prime.');
Memo.Lines.Add('10,000th Prime = '+IntToStr(Sieve.Primes[10000-1]));
finally Sieve.Free; end;
end;
 
</syntaxhighlight>
{{out}}
<pre>
Showing the first twenty primes
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
 
Showing the primes between 100 and 150.
101 103 107 109 113 127 131 137 139 149
 
Showing the number of primes between 7,700 and 8,000.
Count = 30
 
Showing the 10,000th prime.
10,000th Prime = 104729
Elapsed Time: 19.853 ms.
 
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
fastfunc nprim num .
repeat
i = 2
while i <= sqrt num and num mod i <> 0
i += 1
.
until num mod i <> 0
num += 1
.
return num
.
prim = 2
primcnt = 1
proc nextprim . .
prim = nprim (prim + 1)
primcnt += 1
.
for i to 20
write prim & " "
nextprim
.
print ""
while prim < 100
nextprim
.
while prim <= 150
write prim & " "
nextprim
.
print ""
while prim < 7700
nextprim
.
while prim <= 8000
cnt += 1
nextprim
.
print cnt
while primcnt < 10000
nextprim
.
print prim
while primcnt < 100000
nextprim
.
print prim
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Standard prime functions handle numbers < 2e+9. See [http://www.echolalie.org/echolisp/help.html#prime?] . The '''bigint''' library handles large numbers. See [http://www.echolalie.org/echolisp/help.html#bigint.lib]. The only limitations are time, memory, and browser performances ..
<langsyntaxhighlight lang="lisp">
; the first twenty primes
(primes 20)
Line 1,133 ⟶ 1,778:
(prime? (1+ (factorial 116))) → #t
 
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
 
The [[Sieve_of_Eratosthenes#Elixir]] Task page lists two "infinite" extensible generators at the bottom. The first of those, using a (hash) Map is reproduced here along with the code to fulfill the required tasks:
<langsyntaxhighlight lang="elixir">defmodule PrimesSoEMap do
@typep stt :: {integer, integer, integer, Enumerable.integer, %{integer => integer}}
 
Line 1,200 ⟶ 1,845:
:timer.tc(testfunc)
|> (fn {t,_} ->
IO.puts "This test bench took #{t} microseconds." end).()</langsyntaxhighlight>
{{output}}
<pre>The first 20 primes are:
Line 1,223 ⟶ 1,868:
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Sieve_of_Eratosthenes#Unbounded_Page-Segmented_Bit-Packed_Odds-Only_Mutable_Array_Sieve Unbounded_Page-Segmented_Bit-Packed Odds-Only Mutable Array Sieve F#]
===The functions===
<langsyntaxhighlight lang="fsharp">
let primes64()=letprimeZ fN pz=primes()|>Seq.unfold(fun ing-> let rec pSome()=seq{yieldfN(int64(pzg()));yield!, p(g)} in p()
let primesI() =primeZ bigint
let primes32()=let pz=primes() in let rec p()=seq{yield(int32(pz()));yield! p()} in p()
let primes64() =primeZ int64
let primes=primes32()
let primes32() =primeZ int32
let pCache = Seq.cache(primes32())
let pCache =Seq.cache(primes32())
let isPrime g=if g<2 then false else let mx=int(sqrt(float g)) in pCache|>Seq.takeWhile(fun n->n<=mx)|>Seq.forall(fun n->g%n>0)
let isPrime g=if g<2 then false else let mx=int(sqrt(float g)) in pCache|>Seq.takeWhile(fun n->n<=mx)|>Seq.forall(fun n->g%n>0)
let isPrime64 g=if g<2L then false else let mx=int(sqrt(float g)) in pCache|>Seq.takeWhile(fun n->n<=mx)|>Seq.forall(fun n->g%(int64 n)>0L)
</syntaxhighlight>
</lang>
 
===The Task===
<langsyntaxhighlight lang="fsharp">
Seq.take 20 primesprimes32()|> Seq.iter (fun n-> printf "%d " n)
</syntaxhighlight>
</lang>
{{out}}
<pre>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
</pre>
<langsyntaxhighlight lang="fsharp">
primesprimes32() |> Seq.skipWhile (fun n->n<100) |> Seq.takeWhile (fun n->n<=150) |> Seq.iter (fun n -> printf "%d " n)
</syntaxhighlight>
</lang>
{{out}}
<pre>
101 103 107 109 113 127 131 137 139 149
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "%d" (primesprimes32() |> Seq.skipWhile (fun n->n<7700) |> Seq.takeWhile (fun n->n<=8000) |> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,256 ⟶ 1,902:
</pre>
To demonstrate extensibility I find the 10000th prime.
<langsyntaxhighlight lang="fsharp">
Seq.item 9999 pCache
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,265 ⟶ 1,911:
</pre>
I then find the 10001st prime which takes less time.
<langsyntaxhighlight lang="fsharp">
Seq.item 10000 pCache
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,273 ⟶ 1,919:
val it : int = 104743
</pre>
To indiccate speed I time the following:
<lang fsharp>printfn "The first 20 primes are: %s"
<syntaxhighlight lang="fsharp">
let strt = System.DateTime.Now.Ticks
for i = 1 to 8 do
let n = pown 10 i // the item index below is zero based!
printfn "The %dth prime is: %A" n (primeZ int |> Seq.item (n - 1))
let timed = (System.DateTime.Now.Ticks - strt) / 10000L
printfn "All of the last took %d milliseconds." timed
</syntaxhighlight>
{{out}}
<pre>
The 10th prime is: 29
The 100th prime is: 541
The 1000th prime is: 7919
The 10000th prime is: 104729
The 100000th prime is: 1299709
The 1000000th prime is: 15485863
The 10000000th prime is: 179424673
The 100000000th prime is: 2038074743
All of the last took 7937 milliseconds.
</pre>
<syntaxhighlight lang="fsharp">printfn "The first 20 primes are: %s"
( primesSeq() |> Seq.take 20
|> Seq.fold (fun s p -> s + string p + " ") "" )
Line 1,288 ⟶ 1,955:
printfn "The %dth prime is: %A" n (primesSeq() |> Seq.item (n - 1))
let timed = (System.DateTime.Now.Ticks - strt) / 10000L
printfn "All of the last took %d milliseconds." timed</langsyntaxhighlight>
 
{{out}}
<pre>The first 20 primes are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
Line 1,310 ⟶ 1,976:
 
Factor's <code>fixnums</code> automatically promote to <code>bignums</code> when large enough, so there are no limits to its prime generator other than the capabilities of the machine it's running on.
<langsyntaxhighlight lang="factor">USING: io math.primes prettyprint sequences ;
 
"First 20 primes: " write
Line 1,322 ⟶ 1,988:
 
"10,000th prime: " write
10,000 nprimes last .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,357 ⟶ 2,023:
The variables are all the default thirty-two bit two's complement integers and integer overflow is a possibility, especially because someone is sure to wonder what is the largest prime that can be represented in thirty-two bits - see the output. The code would be extensible in another way, if all appearances of <code>INTEGER</code> were to be replaced by <code>INTEGER*8</code> though not all variables need be changed - such as <code>C</code> and <code>B</code> because they need only index a character in array SCHARS or a bit in a character. Using sixty-four bits for such variables is excessive even if the cpu uses a 64-bit data bus to memory. If such a change were to be made, then all would go well as cpu time and disc space were consumed up to the point when the count of prime numbers can no longer be fitted into the four character storage allowance in the record format. This will be when more than 4,294,967,295 primes have been counted (with 64-bit arithmetic its four bytes will manifest as an unsigned integer) in previous records, and Prime(4,294,967,295) = 104,484,802,043, so that the bit file would require a mere 6,530MB or so - which some may think is not too much. If so, expanding the allowance from four to five characters would be easy enough, and then 256 times as many primes could be counted. That would also expand the reach of the record counter, which otherwise would be limited to 4,294,967,295 records of 4096 bytes each, or a bit bag of 17,592,186,040,320 bytes - only seventeen terabytes...
 
Overflow is also a problem in many of the calculations. For instance, for a given (prime) number F, the marking of multiples of F via the sieve process starts with the bit corresponding to F² and if this exceeds the number corresponding to the last bit of the current sieve span, then the sieve process is complete for this span because all later values for F will be still further past the end. So, if <code>LST</code> is the number corresponding to the last bit of the current span, <langsyntaxhighlight Fortranlang="fortran"> DO WHILE(F*F <= LST) !But, F*F might overflow the integer limit so instead,
DO WHILE(F <= LST/F) !Except, LST might also overflow the integer limit, so
DO WHILE(F <= (IST + 2*(SBITS - 1))/F) !Which becomes...
DO WHILE(F <= IST/F + (MOD(IST,F) + 2*(SBITS - 1))/F) !Preserving the remainder from IST/F.</langsyntaxhighlight>
Except, <code>IST</code> might overflow the integer limit, in which case function PSURGE declares itself unable to proceed and returns ''false''.
 
Line 1,372 ⟶ 2,038:
Although recursion is now permissible if one utters the magic word <code>RECURSIVE</code>, this ability usually is not extended to the workings for formatted I/O so that if say a function is invoked in a WRITE statement's list, should that function attempt to use a WRITE statement, the run will be stopped. There can be slight dispensations if different types of WRITE statement are involved (say, formatted for one, and "free"-format for the other) but an ugly message is the likely result. The various functions are thus best invoked via an assignment statement to a scratch variable, which can then be printed. The functions are definitely not "pure" because although they are indeed functions only of their arguments, they all mess with shared storage, can produce error messages (and even a STOP), and can provoke I/O with a disc file, even creating such a file. For this reason, it would be unwise to attempt to invoke them via any sort of parallel processing. Similarly, the disc file is opened with exclusive use because of the possibility of writing to it. There are no facilities in standard Fortran to control the locking and unlocking of records of a disc file as would be needed when adding a new record and updating the record count. This would be needed if separate tasks could be accessing the bit file at the same time, and is prevented by exclusive use. If an interactive system were prepared to respond to requests for ISPRIME(n), ''etc.'' it should open the bit file only for its query then close it before waiting for the next request - which might be many milliseconds away.
 
The bit array is stored in an array of type CHARACTER*1 since this has been available longer and more widely than INTEGER*1. One hopes that the consequent genuflections to type checking via functions CHAR(i) and ICHAR(c) will not involve an overhead. <langsyntaxhighlight Fortranlang="fortran"> MODULE PRIMEBAG !Need prime numbers? Plenty are available.
C Creates and expands a disc file for a sieve of Eratoshenes, representing odd numbers only and starting with three.
C Storage requirements: an array of N prime numbers in 16/32/64 bits vs. a bit array up to the 16/32/64 bit limit.
Line 1,769 ⟶ 2,435:
END DO !On to the next in the list.
 
END !Whee!</langsyntaxhighlight>
Although the structuralist talk up the merit of "structured" constructs in programming, there are often annoying obstacles. With a WHILE-loop one usually has to repeat the "next item" code to "prime" the loop, as in <langsyntaxhighlight Fortranlang="fortran"> P = NEXTPRIME(100)
DO WHILE (P.LE.150)
...stuff...
P = NEXTPRIME(P)
END DO</langsyntaxhighlight>
While this is not a large imposition in this example, if Fortran were to allow assignment within expressions as in Algol, the tedium of code replication and its risks could be avoided. <langsyntaxhighlight lang="algol68"> P:=100; WHILE (P:=NextPrime(P)) <= 150 DO stuff;</langsyntaxhighlight> If instead of NEXTPRIME the "next item" code was to read a record of a disc file, the repetition needed becomes tiresome. So, an IF-statement, and ... a GO TO...
 
===The Results===
Line 1,826 ⟶ 2,492:
 
The thinning out rather suggests an alternative encoding such as by counting the number of "off" bits until the next "on" bit, but this would produce a variable-length packing so that it would no longer be easy to find the bit associated with a given number by something so simple as <code>R = (NN - SORG)/(2*SBITS)</code> as in NEXTPRIME. A more accomplished data compression system might instead offer a reference to a library containing a table of prime numbers, or even store the code for a programme that will generate the data. File Pbag.for is 23,008 bytes long, and of course contains irrelevant commentary and flabby phrases such as "PARAMETER", "INTEGER", "GRASPPRIMEBAG", ''etc''. As is the modern style, the code file is much larger at 548,923 bytes (containing kilobyte sequences of hex CC and of 00), but both are much smaller than the 134,352,896 bytes of file PrimeSieve.bit.
===Alternative Version using the Sorenson Sieve===
This version is written in largely Fortran-77 style (fixed form, GO TO) It uses the dynamic array algorithm as described in the paper, "Two Compact Incremental Prime Sieves" by Jonathon P. Sorenson. The sieve is limited to an upper bound of 2^31 (in Fortran, integers are always signed) To be correct for that upper limit, signed overflow that can occur for items in the buckets (8 16-bit signed integers) must be taken into account.
 
This code is also written in old style in that the generator uses statically allocated variables to maintain state. It is not re-entrant and there can only be one generator in use at a time. That's more in line with programming practices in the 70s and 80s.
=={{header|FreeBASIC}}==
This program uses the Sieve Of Eratosthenes which is not very efficient for large primes but is quick enough for present purposes.
 
In Fortran, dynamic arrays are always exactly allocated without any over capacity for later expansion, so naively re-allocating the array by 2 as specified in the original paper results in a significant drop in performance due to all of the memory moves. Therefore, this implementation keeps track of the array size which will be less than the array capacity.
The size of the sieve array (of type Boolean) is calculated as 20 times the number of primes required which is big enough to compute
<syntaxhighlight lang="Fortran">
up to 50 million primes (a sieve size of 1 billion bytes) which takes under 50 seconds on my i3 @ 2.13 GHz. I've limited the
* incremental Sieve of Eratosthenes based on the paper,
procedure to this but it should certainly be possible to use a much higher figure without running out of memory.
* "Two Compact Incremental Prime Sieves"
 
SUBROUTINE nextprime(no init, p)
It would also be possible to use a more efficient algorithm to compute the optimal sieve size for smaller numbers of primes but this will suffice for now.
IMPLICIT NONE
INTEGER*2, SAVE, ALLOCATABLE :: sieve(:,:)
INTEGER, SAVE :: r, s, pos, n, f1, f2, sz
INTEGER i, j, d, next, p, f3
LOGICAL no init, is prime
 
IF (no init) GO TO 10
<lang freebasic>' FB 1.05.0
IF (ALLOCATED(sieve)) DEALLOCATE(sieve)
 
* Each row in the sieve is a stack of 8 short integers. The
Enum SieveLimitType
* stacks will never overflow since the product 2*3*5 ... *29
number
* (10 primes) exceeds a 32 bit integer. 2 is not stored in the sieve.
between
countBetween
End Enum
 
ALLOCATE(sieve(8,3))
Sub printPrimes(low As Integer, high As Integer, slt As SieveLimitType)
sieve = reshape([(0_2, i = 1, 24)], shape(sieve))
If high < low OrElse low < 1 Then Return ' too small
r = 3
If slt <> number AndAlso slt <> between AndAlso slt <> countBetween Then Return
s = 9
If slt <> number AndAlso (low < 2 OrElse high < 2) Then Return
pos = 1
If slt <> number AndAlso high > 1000000000 Then Return ' too big
sz = 1 ! sieve starts with size = 1
If slt = number AndAlso high > 50000000 Then Return ' too big
f1 = 2 ! Fibonacci sequence for allocating new capacities
Dim As Integer n
f2 = 3 ! array starts with capacity 3
If slt = number Then
n = 1
n = 20 * high '' big enough to accomodate 50 million primes to which this procedure is limited
p = 2 ! return our first prime
Else
n = highRETURN
End If
Dim a(2 To n) As Boolean '' only uses 1 byte per element
For i As Integer = 2 To n : a(i) = True : Next '' set all elements to True to start with
Dim As Integer p = 2, q
' mark non-prime numbers by setting the corresponding array element to False
 
10 n = n + 2
Do
For j Asis Integerprime = p * p To n Step p.true.
IF (sieve(1, pos) .eq. 0) GO TO 20 ! n is non-smooth w.r.t sieve
a(j) = False
is prime = .false. ! element at sieve(pos) divides n
Next j
' look forDO next17, Truei element= in1, array after 'p'8
q = 0
For j As Integer = p + 1 To Sqr(n)
If a(j) Then
q = j
Exit For
End If
Next j
If q = 0 Then Exit Do
p = q
Loop
 
Clear the stack of divisors by moving them to the next multiple
Select Case As Const slt
Case number
Dim count As Integer = 0
For i As Integer = 2 To n
If a(i) Then
count += 1
If count >= low AndAlso count <= high Then
Print i; " ";
End If
If count = high Then Exit Select
End If
Next
 
d = sieve(i, pos)
Case between
For i AsIF Integer(d =.eq. low0) ToGO highTO 20 ! stack is empty
IfIF a(id .lt. 0) Thend = d + 65536 ! correct storage overflow
sieve(i, pos) Print i; "= ";0
Endnext if= mod(pos + d - 1, sz) + 1
Next
 
* Push divisor d on to the stack of the next multiple
Case countBetween
Dim count As Integer = 0
For i As Integer = low To high
If a(i) Then count += 1
Next
Print count;
 
j = 1
End Select
12 IF (sieve(j, next) .eq. 0) GO TO 15
Print
j = j + 1
End Sub
GO TO 12
15 sieve(j, next) = d
17 CONTINUE
 
Check if n is square; if so, then add sieving prime and advance
Print "The first 20 primes are :"
 
Print
20 IF (n .lt. s) GO TO 30
printPrimes(1, 20, number)
IF (.not. is prime) GO TO 25
Print
is prime = .false. ! r = √s divides n
Print "The primes between 100 and 150 are :"
next = mod(pos + r - 1, sz) + 1 ! however, r is prime, insert it.
Print
 
printPrimes(100, 150, between)
j = 1
Print
22 IF (sieve(j, next) .eq. 0) GO TO 23
Print "The number of primes between 7700 and 8000 is :";
j = j + 1
printPrimes(7700, 8000, countBetween)
GO TO 22
Print
23 sieve(j, next) = r
Print "The 10000th prime is :";
 
Dim t As Double = timer
25 r = r + 2
printPrimes(10000, 10000, number)
s = r**2
Print "Computed in "; CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "The 1000000th prime is :";
t = timer
printPrimes(1000000, 1000000, number)
Print "Computed in ";CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "The 50000000th prime is :";
t = timer
printPrimes(50000000, 50000000, number)
Print "Computed in ";CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "Press any key to quit"
Sleep</lang>
 
Continue to the next array slot; grow the array by two when
* we get to the end to maintain the invariant size(sieve) > √n
* IF the size exceeds the array capacity, resize the arary.
 
30 pos = pos + 1
IF (pos .le. sz) GO TO 40
sz = sz + 2
pos = 1
 
IF (sz .le. f2) GO TO 40 ! so far, no need to grow
f3 = f1 + f2
f1 = f2
f2 = f3
sieve = reshape(sieve, [8, f2],
& pad = [(0_2, i = 1, 8*(f2 - f1))])
 
* Either return n back to the caller or circle back if n
* turned out to be composite.
 
40 IF (.not. is prime) GO TO 10
p = n
END SUBROUTINE
</syntaxhighlight>
The driver code:
<syntaxhighlight lang="fortran">
INCLUDE 'sieve.f'
 
PROGRAM RC Extensible Sieve
IMPLICIT INTEGER (A-Z)
 
WRITE (*, '(A)', advance='no')
& 'The first 20 primes:'
 
CALL nextprime(.false., p)
DO 10, i = 1, 20
WRITE (*, '(I3)', advance = 'no') p
10 CALL nextprime(.true., p)
WRITE (*, *)
 
WRITE (*, '(A)', advance = 'no')
& 'The primes between 100 and 150:'
 
20 CALL nextprime(.true., p)
IF (p .gt. 149) GO TO 30
IF (p .gt. 99)
& WRITE (*, '(I4)', advance = 'no') p
GO TO 20
30 WRITE (*, *)
 
count = 0
40 CALL nextprime(.true., p)
IF (p .gt. 7999) GO TO 50
IF (p .gt. 7700) count = count + 1
GO TO 40
50 WRITE (*, 100) count
100 FORMAT ('There are ', I0, ' primes between 7700 and 8000.')
 
CALL nextprime(.false., p) ! re-initialize
target = 1 ! target count
n = 0 ! number of primes generated
60 n = n + 1
IF (n .lt. target) GO TO 70
WRITE (*, '(ES7.1,1X,I12)'), real(n), p
IF (target .eq. 100 000 000) GO TO 80
target = target * 10
70 CALL nextprime(.true., p)
GO TO 60
 
80 END
</syntaxhighlight>
{{Out}}
<pre>
The first 20 primes: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
The primes between 100 and 150: 101 103 107 109 113 127 131 137 139 149
There are 30 primes between 7700 and 8000.
1.0E+00 2
1.0E+01 29
1.0E+02 541
1.0E+03 7919
1.0E+04 104729
1.0E+05 1299709
1.0E+06 15485863
1.0E+07 179424673
1.0E+08 2038074743
</pre>
 
=={{header|Frink}}==
Frink has built-in functions for efficiently enumerating through prime numbers, including <CODE>primes</CODE>, <CODE>nextPrime</CODE>, and <CODE>previousPrime</CODE>, and <CODE>isPrime</CODE>. These functions handle arbitrarily-large integers.
<syntaxhighlight lang="frink">println["The first 20 primes are: " + first[primes[], 20]]
println["The primes between 100 and 150 are: " + primes[100,150]]
println["The number of primes between 7700 and 8000 are: " + length[primes[7700,8000]]]
println["The 10,000th prime is: " + nth[primes[], 10000-1]] // nth is zero-based</syntaxhighlight>
{{out}}
<pre>
The first 20 primes are : [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
The primes between 100 and 150 are: [101, 103, 107, 109, 113, 127, 131, 137, 139, 149]
The number of primes between 7700 and 8000 are: 30
The 10,000th prime is: 104729
</pre>
 
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
 
=={{header|FutureBasic}}==
The primes between 100 and 150 are :
<syntaxhighlight lang="futurebasic">
local fn IsPrime( n as NSUInteger ) as BOOL
BOOL isPrime = YES
NSUInteger i
if n < 2 then exit fn = NO
if n = 2 then exit fn = YES
if n mod 2 == 0 then exit fn = NO
for i = 3 to int(n^.5) step 2
if n mod i == 0 then exit fn = NO
next
end fn = isPrime
 
101 103 107 109 113 127 131 137 139 149
 
local fn ExtensiblePrimes
The number of primes between 7700 and 8000 is : 30
long c = 0, n = 2, count = 0, track = 0
printf @"The first 20 prime numbers are: "
while ( c < 20 )
if ( fn IsPrime(n) )
printf @"%ld \b", n
c++
end if
n++
wend
printf @"\n\nPrimes between 100 and 150 include: "
for n = 100 to 150
if ( fn IsPrime(n) ) then printf @"%ld \b", n
next
printf @"\n\nPrimes beween 7,700 and 8,000 include: "
c = 0
for n = 7700 to 8000
if ( fn IsPrime(n) ) then c += fn IsPrime(n) : printf @"%ld \b", n : count++ : track++
if count = 10 then print : count = 0
next
printf @"There are %ld primes beween 7,700 and 8,000.", track
printf @"\nThe 10,000th prime is: "
c = 0 : n = 1
while ( c < 10000 )
n++
c += fn IsPrime(n)
wend
printf @"%ld", n
end fn
 
CFTimeInterval t
The 10000th prime is : 104729
Computed in 8 ms
 
t = fn CACurrentMediaTime
The 1000000th prime is : 15485863
fn ExtensiblePrimes
Computed in 775 ms
printf @"\nCompute time: %.3f ms",(fn CACurrentMediaTime-t)*100
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
The first 20 prime numbers are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
 
Primes between 100 and 150 include:
The 50000000th prime is : 982451653
101 103 107 109 113 127 131 137 139 149
Computed in 46703 ms
 
Primes beween 7,700 and 8,000 include:
7703 7717 7723 7727 7741 7753 7757 7759 7789 7793
7817 7823 7829 7841 7853 7867 7873 7877 7879 7883
7901 7907 7919 7927 7933 7937 7949 7951 7963 7993
There are 30 primes beween 7,700 and 8,000.
 
The 10,000th prime is:
104729
 
Compute time: 73.034 ms
</pre>
 
 
=={{header|Go}}==
An implementation of "The Genuine Sieve of Eratosthenese" by Melissa E. O'Niell. This is the paper cited above in the "Faster Alternative Version" of D. The Go example here though strips away optimizations such as a wheel to show the central idea of storing prime multiples in a queue data structure.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,046 ⟶ 2,832:
*p = q[:last]
return e
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,059 ⟶ 2,845:
Due to how Go's imports work, the bellow can be given directly to "<code>go run</code>" or "<code>go build</code>" and the latest version of the primegen package will be fetched and built if it's not already present on the system.
(This example may not be exactly within the scope of this task, but it's a trivial to use and extremely fast prime generator probably worth considering whenever primes are needed in Go.)
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,085 ⟶ 2,871:
}
fmt.Println("10,000th prime:", p.Next())
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 2,095 ⟶ 2,881:
This program uses the [http://hackage.haskell.org/package/primes primes] package, which uses a lazy wheel sieve to produce an infinite list of primes.
 
<langsyntaxhighlight lang="haskell">#!/usr/bin/env runghc
 
import Data.List
Line 2,120 ⟶ 2,906:
print $ genericLength $ primesBetweenInclusive 7700 8000
putStr "The 10000th prime: "
print $ nthPrime 10000</langsyntaxhighlight>
 
{{out}}
Line 2,133 ⟶ 2,919:
Using list based unbounded sieve from [[Sieve_of_Eratosthenes#With_Wheel|here]] (runs instantly):
 
<langsyntaxhighlight lang="haskell"> λ> take 20 primesW
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71]
 
Line 2,143 ⟶ 2,929:
 
λ> (!! (10000-1)) primesW
104729</langsyntaxhighlight>
 
[[File:Example.jpg]]
 
=== Using analytic formula for primes ===
{{Works with|GHC|8.10.7}}
{{Works with|primes|0.2.1.0}}
{{Works with|exact-real|0.12.5.1}}
 
There are analytic functions to generate primes. One of such formula is the following:
: p(''n'') = [2''n'' (2''n''+1) {(2''n''-1)! ''C''}]
here [''x''] is the integral part of ''x'', {''x''} is the fractional part of ''x'', and ''C'' is a real constant (similar to [https://en.wikipedia.org/wiki/Mills%27_constant Mill's constant]). We can prove that there is a constant ''C'', such that p(''n'') is exactly the ''n''th prime number for any natural number ''n''. The first digits of ''C'' are ''C''=0.359344964622775339841352348439200241924659634...
Haskell have [https://hackage.haskell.org/package/exact-real-0.12.5.1/docs/Data-CReal.html a library of constructive real numbers], where real numbers can be of an arbitrary precision. We can define this constant ''C'' '''exactly''' and use the above formula to calculate the ''n''th prime. This is not the fastest method, but one of the coolest. And it is not as bad as you may think. It took about 0.3 seconds to calculate 10,000th prime using this formula.
 
<syntaxhighlight lang="haskell">
{-# LANGUAGE PostfixOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
 
import Data.Numbers.Primes
import Data.Array.Unboxed hiding ((!))
import qualified Data.Array.Unboxed as Array
import Data.CReal
import Data.CReal.Internal
import GHC.TypeLits
 
instance KnownNat n => Enum (CReal n) where
toEnum i = fromIntegral i
fromEnum _ = error "Cannot fromEnum CReal"
enumFrom = iterate (+ 1)
enumFromTo n e = takeWhile (<= e) $ iterate (+ 1)n
enumFromThen n m = iterate (+(m-n)) n
enumFromThenTo n m e = if m >= n then takeWhile (<= e) $ iterate (+(m-n)) n
else takeWhile (>= e) $ iterate (+(m-n)) n
 
 
-- partial_sum x y a b = (p,q) where
-- p/q = sum_{a<i<=b} x(i) / poduct_{a<j<=j} y(j)
-- The complexity of partial_sum x y 0 n is O(n log n)
partial_sum x y = pq where
pq a b = if a>=b then (0,1)
else if a==b-1 then (fromIntegral $ x b, fromIntegral $ y b )
else (p_ab,q_ab)
where
c=(a+b) `div` 2
(p_ac,q_ac) = pq a c
(p_cb,q_cb) = pq c b
p_ab = p_cb + q_cb*p_ac
q_ab = q_ac*q_cb
 
-- c is the real constant that is used in the formula for primes
-- c = sum_{1<i} p_i / (2i+1)!
-- where p_i is i-th prime.
-- This will work for any sequence of integers p, where |p_n| < 2n(2n+1) * 0.375
c = crMemoize f where
f n = 2^n * p `div` q where
n' = fromIntegral n
u = head [ceiling (x) | x<-[(n' * log 2/ (log n'-1)/2 ) ..] , 2*x*log (2*x) - 2*x > n'*log 2]
-- Invariant: (2u+1)! > 2^n
ar :: UArray Int Int
ar = listArray (1,u) $ primes
(p,q) = partial_sum (ar Array.!) (\n-> 2*n*(2*n+1) ) 0 u
 
 
-- Fractorial part of x
-- By definition it is in the interval [-0.5; 0.5]
-- But it gurantes to work corectly if fractional part of x is in (-0.375; 0.375)
fract x = x - fromIntegral (round (x :: CReal 3))
 
-- Factorial.
-- The complexity of (n!) is O(n log n) (which is better than O(n^2) for product [1..n] )
(!) :: (RealFrac a, Num b) => a -> b
(!) = fromIntegral . snd . partial_sum (const 0) id 0 . round
 
-- Analytic function for n-th prime.
-- NB. Strictly speaking this function is not analytic, because it uses factorial, fractional part and round functions
-- To make it truly analytic you need to replace
-- fract x = acos (cos (2*pi*x)) / (2*pi)
-- round x = x - fract x
-- and use the Gamma function instead of factorial.
-- Then you will get analytic function prime :: CReal 0 -> CReal 0
 
prime n = round( 2*n*(2*n+1) * fract ( c * ((2*n-1)!)))</syntaxhighlight>
 
Then you can use this function:
<syntaxhighlight lang="haskell">
λ> :set +s
λ> prime 10000
104729
(0.32 secs, 179,899,272 bytes)
λ> length $ dropWhile (< 7700) $ takeWhile (< 8000) $ map prime [1..]
30
(3.09 secs, 3,418,225,920 bytes)
λ> dropWhile (< 100) $ takeWhile (< 150) $ map prime [1..]
[101,103,107,109,113,127,131,137,139,149]
(0.02 secs, 20,239,464 bytes)
λ> map prime [1..20]
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71]
(0.01 secs, 10,485,208 bytes)
</syntaxhighlight>
 
==Icon and {{header|Unicon}}==
Line 2,150 ⟶ 3,035:
 
The expression:
<langsyntaxhighlight lang="unicon">![2,3,5,7] | (nc := 11) | (nc +:= |wheel2345)</langsyntaxhighlight>
is an open-ended sequence generating potential primes.
 
<langsyntaxhighlight lang="unicon">import Collections # to get the Heap class for use as a Priority Queue
record filter(composite, prime) # next composite involving this prime
 
Line 2,190 ⟶ 3,075:
 
# Provide a function for comparing filters in the priority queue...
procedure getCompositeField(x); return x.composite; end</langsyntaxhighlight>
 
{{out}}
Line 2,206 ⟶ 3,091:
Using the p: builtin, http://www.jsoftware.com/help/dictionary/dpco.htm reports "Currently, arguments larger than 2^31 are tested to be prime according to a probabilistic algorithm (Miller-Rabin)".
 
<langsyntaxhighlight Jlang="j"> p:i.20
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
(#~ >:&100)i.&.(p:inv) 150
Line 2,213 ⟶ 3,098:
30
p:10000-1
104729</langsyntaxhighlight>
 
Note: p: gives the nth prime, where 0 is first, 1 is second, 2 (cardinal) is third (ordinal) and so on...
Line 2,219 ⟶ 3,104:
Note: 4&p: gives the next prime
 
<langsyntaxhighlight Jlang="j"> 4 p: 104729
104743</langsyntaxhighlight>
 
=={{header|Java}}==
Based on my second C++ solution, which in turn was based on the C solution.
<langsyntaxhighlight lang="java">import java.util.*;
 
public class PrimeGenerator {
Line 2,337 ⟶ 3,222:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,365 ⟶ 3,250:
Sounds a bit weird, but I hope it will be intelligible by the testing examples below. First the code:
 
<langsyntaxhighlight JavaScriptlang="javascript">function primeGenerator(num, showPrimes) {
var i,
arr = [];
Line 2,405 ⟶ 3,290:
// (surrogate for a quite long and detailed try-catch-block anywhere before)
throw("Invalid arguments for primeGenerator()");
}</langsyntaxhighlight>
 
'''Test'''
<syntaxhighlight lang="text">// first 20 primes
console.log(primeGenerator(20, true));
 
Line 2,418 ⟶ 3,303:
 
// the 10,000th prime
console.log(primeGenerator(10000, false));</langsyntaxhighlight>
 
'''Output'''
<syntaxhighlight lang="text">Array [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 51, 59, 61, 67, 71 ]
 
Array [ 101, 103, 107, 109, 113, 127, 131, 137, 139, 149 ]
Line 2,427 ⟶ 3,312:
30
 
104729</langsyntaxhighlight>
 
=={{header|jq}}==
Line 2,441 ⟶ 3,326:
 
'''Preliminaries:'''
<langsyntaxhighlight lang="jq"># Recent versions of jq include the following definition:
# until/2 loops until cond is satisfied,
# and emits the value satisfying the condition:
Line 2,449 ⟶ 3,334:
_until;
 
def count(cond): reduce .[] as $x (0; if $x|cond then .+1 else . end);</langsyntaxhighlight>
 
'''Prime numbers:'''
<langsyntaxhighlight lang="jq"># Is the input integer a prime?
# "previous" must be the array of sorted primes greater than 1 up to (.|sqrt)
def is_prime(previous):
Line 2,484 ⟶ 3,369:
def primes_upto(n):
until( .[length-1] > n; extend_primes )
| if .[length-1] > n then .[0:length-1] else . end;</langsyntaxhighlight>
'''The tasks:'''
The tasks are completed separately here to highlight the fact that by using "extend_primes", each task can be readily completed without generating unnecessarily many primes.
<langsyntaxhighlight lang="jq">"First 20 primes:", (20 | primes), "",
 
"Primes between 100 and 150:",
Line 2,495 ⟶ 3,380:
 
(( primes_upto(8000) | count( . > 7700) | length) as $length
| "There are \($length) primes twixt 7700 and 8000.")</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -r -c -n -f Extensible_prime_generator.jq
First 20 primes:
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71]
Line 2,506 ⟶ 3,391:
The 10,000th prime is 104729
 
There are 30 primes twixt 7700 and 8000.</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 2,514 ⟶ 3,399:
and by default determines primes with Knuth's recommended level for cryptography of an error less than
(0.25)^25 = 8.881784197001252e-16, or 1 in 1125899906842624.
<langsyntaxhighlight lang="julia">using Primes
 
sum = 2
Line 2,534 ⟶ 3,419:
println("the primes between 100 and 150 are ", primes(100,150))
println("The number of primes between 7,700 and 8,000 is ", length(primes(7700, 8000)))
println("The 10,000th prime is ", prime(10000))</langsyntaxhighlight>
{{output}}
<pre>
Line 2,547 ⟶ 3,432:
 
The above code just uses the "Primes" package as a set of tools to solve the tasks. The following code creates a very simple generator using `isprime` inside a iterator and then uses that to solve the tasks:
<langsyntaxhighlight lang="julia">using Primes: isprime
 
PrimesGen() = Iterators.filter(isprime, Iterators.countfrom(Int64(2)))
Line 2,565 ⟶ 3,450:
end
println("The 10,000th prime: ", Iterators.first(Iterators.drop(PrimesGen(), 9999)))
println()</langsyntaxhighlight>
 
This outputs:
Line 2,576 ⟶ 3,461:
 
To show it's speed, lets use it to solve the Euler Problem 10 of calculating the sum of the primes to two million as follows:
<langsyntaxhighlight lang="julia">using Printf: @printf
@time let sm = 0
for p in Iterators.filter(isprime, Iterators.countfrom(UInt64(2)))
p > 2000000 && break
sm += p
end; @printf("%d\n", sm) end</langsyntaxhighlight>
 
which outputs:
Line 2,595 ⟶ 3,480:
 
The above code is more than adequate to solve the trivial tasks as required here, but is really too slow for "industrial strength" tasks for ranges of billions. The following code uses the Page Segmented Algorithm from [[Sieve_of_Eratosthenes#Julia]] to solve the task:
<langsyntaxhighlight lang="julia">using Printf: @printf
 
print("Sum of first 100,000 primes: ")
Line 2,610 ⟶ 3,495:
end; println("Number of primes between 7700 and 8000: ", cnt)
end
@printf("The 10,000th prime: %d\n", Iterators.first(Iterators.drop(PrimesPaged(), 9999)))</langsyntaxhighlight>
 
to produce the same output much faster.
 
To show how much faster it is, doing the same Euler Problem 10 as follows:
<langsyntaxhighlight lang="julia">using Printf: @printf
@time let sm = 0
for p in PrimesPaged()
p > 2000000 && break
sm += p
end; @printf("%d\n", sm) end</langsyntaxhighlight>
 
produces:
Line 2,634 ⟶ 3,519:
Although we could use the java.math.BigInteger type to generate arbitrarily large primes, there is no need to do so here as the primes to be generated are well within the limits of the 4-byte Int type.
((workwith|Kotlin|version 1.3}}
<langsyntaxhighlight lang="scala">fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
Line 2,663 ⟶ 3,548:
println("Number of primes between 7700 and 8000 = ${primes.filter { it in 7700..8000 }.count()}")
println("10,000th prime = ${primes.last()}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,678 ⟶ 3,563:
 
The following odds-only incremental Sieve of Eratosthenes generator has O(n log (log n)) performance due to using a (mutable) HashMap:
<langsyntaxhighlight lang="scala">fun primesHM(): Sequence<Int> = sequence {
yield(2)
fun oddprms(): Sequence<Int> = sequence {
Line 2,710 ⟶ 3,595:
}
yieldAll(oddprms())
}</Langsyntaxhighlight>
 
it is faster than the first example even though not using wheel factorization (other than odds-only) and rapidly pulls far ahead of it with increasing range such that it is usable to a range of 100 million in the order of 10 seconds.
Line 2,719 ⟶ 3,604:
 
It can count the primes to one billion in about 15 seconds on a slow tablet CPU (Intel x5-Z8350 at 1.92 Gigahertz) with the following code:
<langsyntaxhighlight lang="kotlin">primesPaged().takeWhile { it <= 1_000_000_000 }.count()</langsyntaxhighlight>
 
Further speed-ups can be achieved of about a factor of four with maximum wheel factorization and by multi-threading by the factor of the effective number of cores used, but there is little point when most of the execution time as a generator is spend iterating over the results.
Line 2,727 ⟶ 3,612:
=={{header|Lua}}==
The modest requirements of this task allow for naive implementations, such as what follows. This generator does not even use its own list of primes to help determine subsequent primes! (though easily fixed) So, it it sufficient, but not efficient.
<syntaxhighlight lang="lua">local primegen = {
<lang lua>-- Extensible prime generator, in Lua, 6/23/2020 db
local primegen = {
count_limit = 2,
value_limit = 3,
Line 2,746 ⟶ 3,630:
needmore = function(self)
return (self.count_limit ~= nil and #self.primelist < self.count_limit)
or (self.value_limit ~= nil and self.primelist[#self.primelist]nextgenvalue < self.value_limit)
end,
generate = function(self, count_limit, value_limit)
Line 2,781 ⟶ 3,665:
 
primegen:generate(100000, nil)
print("The 100,000th prime: " .. primegen.primelist[#primegen.primelist])</langsyntaxhighlight>
{{out}}
<pre>First 20 primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
Line 2,792 ⟶ 3,676:
The following script implements a Sieve of Eratosthenes that is automatically extended when a method call needs a higher upper limit.
 
<langsyntaxhighlight Lingolang="lingo">-- parent script "sieve"
property _sieve
 
Line 2,896 ⟶ 3,780:
end repeat
end repeat
end</langsyntaxhighlight>
 
<langsyntaxhighlight Lingolang="lingo">sieve = script("sieve").new()
put "First twenty primes: " & sieve.getNPrimes(20)
put "Primes between 100 and 150: "& sieve.getPrimesInRange(100, 150)
put "Number of primes between 7,700 and 8,000: " & sieve.getPrimesInRange(7700, 8000).count
put "The 10,000th prime: " & sieve.getNthPrime(10000)</langsyntaxhighlight>
 
{{out}}
Line 2,927 ⟶ 3,811:
Loop statement check a flag in a block of code ({ }), so when the block ends restart again (resetting the loop flag)
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckPrimes {
\\ Inventories are lists, Known and Known1 are pointers to Inventories
Line 3,022 ⟶ 3,906:
}
CheckPrimes
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,048 ⟶ 3,932:
I use same indentation so you can copy it at same position as in example above. A loop statement mark once the current block for restart after then last statement on block.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
PrimeNth=lambda Known, Known1 (n as long) -> {
if n<1 then Error "Only >=1"
Line 3,072 ⟶ 3,956:
x++ : Loop }
}
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Prime and PrimePi use sparse caching and sieving. For large values, the Lagarias–Miller–Odlyzko algorithm for PrimePi is used, based on asymptotic estimates of the density of primes, and is inverted to give Prime.
PrimeQ first tests for divisibility using small primes, then uses the Miller–Rabin strong pseudoprime test base 2 and base 3, and then uses a Lucas test.
<langsyntaxhighlight Mathematicalang="mathematica">Prime[Range[20]]
{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71}
Select[Range[100,150], PrimeQ]
Line 3,084 ⟶ 3,968:
30
Prime[10000]
104729</langsyntaxhighlight>
 
=={{header|Nim}}==
 
For such trivial ranges as the task requirements or solving the Euler Problem 10 of summing the primes to two million, a basic generator such as the hash table based version from the [[Sieve_of_Eratosthenes#Nim_Unbounded_Versions]] section of the Sieve of Eratosthenes task will suffice, as follows:
<langsyntaxhighlight lang="nim">import tables
 
type PrimeType = int
Line 3,148 ⟶ 4,032:
echo "The sum of the primes to two million is: ", sum
break
sum += p</langsyntaxhighlight>
{{output}}
<pre>The first 20 primes are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
Line 3,163 ⟶ 4,047:
 
To use that sieve, just substitute the following in the code:
<syntaxhighlight lang ="nim">for p in primesPaged():</langsyntaxhighlight>
 
wherever the following is in the code:
<syntaxhighlight lang ="nim">for p in iter():</langsyntaxhighlight>
and one doesn't need the lines including `iter` just above these lines at all.
 
As noted in that section, using an extensible generator isn't the best choice for huge ranges as much higher efficiency can be obtained by using functions that deal directly with the composite culled packed-bit array representations directly as the `countPrimesTo` function does. This makes further improvements to the culling efficiency pointless, as even if one were to reduce the culling speed to zero, it still would take several seconds per range of a billion to enumerate the found primes as a generator.
 
=={{header|PARI/GPOCaml}}==
;2-3-5-7-wheel postponed incremental sieve
<syntaxhighlight lang="ocaml">module IntMap = Map.Make(Int)
 
let rec steps =
4 :: 2 :: 4 :: 6 :: 2 :: 6 :: 4 :: 2 :: 4 :: 6 :: 6 :: 2 ::
6 :: 4 :: 2 :: 6 :: 4 :: 6 :: 8 :: 4 :: 2 :: 4 :: 2 :: 4 ::
8 :: 6 :: 4 :: 6 :: 2 :: 4 :: 6 :: 2 :: 6 :: 6 :: 4 :: 2 ::
4 :: 6 :: 2 :: 6 :: 4 :: 2 :: 4 :: 2 :: 10 :: 2 :: 10 :: 2 :: steps
 
let not_in_wheel =
let scan i =
let rec loop n w = n < 223 && (i = n mod 210
|| match w with [] -> assert false | d :: w' -> loop (n + d) w')
in not (loop 13 steps)
in Array.init 210 scan
 
let seq_primes =
let rec calc ms m p2 =
if not_in_wheel.(m mod 210) || IntMap.mem m ms
then calc ms (m + p2) p2
else IntMap.add m p2 ms
in
let rec next c p pp ps whl ms () =
match whl with
| [] -> assert false
| d :: w -> match IntMap.min_binding_opt ms with
| Some (m, p2) when c = m ->
next (c + d) p pp ps w (calc (IntMap.remove m ms) (m + p2) p2) ()
| _ when c < pp -> Seq.Cons (c, next (c + d) p pp ps w ms)
| _ -> match ps () with
| Seq.Cons (p', ps') -> let p2' = p + p in
next (c + d) p' (p' * p') ps' w (calc ms (pp + p2') p2') ()
| _ -> assert false
in
let rec ps () = next 13 11 121 ps steps IntMap.empty () in
Seq.cons 2 (Seq.cons 3 (Seq.cons 5 (Seq.cons 7 (Seq.cons 11 ps))))</syntaxhighlight>
;Test code
<syntaxhighlight lang="ocaml">let seq_show sq =
print_newline (Seq.iter (Printf.printf " %u") sq)
 
let () =
seq_primes |> Seq.take 20 |> seq_show;
seq_primes |> Seq.drop_while ((>) 100) |> Seq.take_while ((>) 150) |> seq_show;
seq_primes |> Seq.drop_while ((>) 7700) |> Seq.take_while ((>) 8000)
|> Seq.length |> Printf.printf " %u primes\n";
seq_primes |> Seq.drop 9999 |> Seq.take 1 |> seq_show</syntaxhighlight>
{{out}}
<pre>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
101 103 107 109 113 127 131 137 139 149
30 primes
104729
</pre>
 
=={{header|PARI/GP}}==
PARI includes a nice prime generator which is quite extensible:
<langsyntaxhighlight lang="c">void
showprimes(GEN lower, GEN upper)
{
Line 3,183 ⟶ 4,121:
pari_printf("%Ps\n", T.pp);
}
}</langsyntaxhighlight>
 
Most of these functions are already built into GP:
<langsyntaxhighlight lang="parigp">primes(20)
primes([100,150])
#primes([7700,8000]) /* or */
s=0; forprime(p=7700,8000,s++); s
prime(10000)</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
Limited to 2.7e14. Much faster than the other Version
<b>there is something wrong </b>
<pre >
http://www.primos.mat.br/Ate100G.html ->
75. de 16639648367 a 16875026921
76. de 16875026963 a 17110593779
77. de 17110593791 a 17346308407
...
my unit:
750000000 16875026921
760000000 17110593779
770000000 17346251243 <----Wrong
</pre>
 
Limited to 2.7e14. Much faster than the other Version. 94s to 257 s for the primes 2..1E11
First the unit.Still a work in progress.
 
Line 3,216 ⟶ 4,141:
./primesieve -t1 100000071680 Sieve size = 256 KiB Threads = 1 100%
Seconds: 19.891 Primes: 4118057696
<langsyntaxhighlight lang="pascal">
unit primsieve;
//{$O+,R+}
{$IFDEF FPC}
{$MODE objFPC}{$Optimization ON,ALL}
{$CODEALIGN proc=32,loop=1}
{$IFEND}
{segmented sieve of Erathostenes using only odd numbers}
Line 3,231 ⟶ 4,154:
function SieveSize :LongInt;
function Nextprime: Uint64;
function StartCount :Uint64;
function TotalCount :Uint64;
function PosOfPrime: Uint64;
Line 3,258 ⟶ 4,182:
{$ALIGN 32}
//prime = FoundPrimesOffset + 2*FoundPrimes[0..FoundPrimesCnt]
FoundPrimes : array[0..12252cSieveSize] of Wordword;
{$ALIGN 32}
sievePrimes : array[0..78498] of tSievePrim;// 1e6^2 ->1e12
// sievePrimes : array[0..1077863664579] of tSievePrim;// maximum 1e14
FoundPrimesOffset : Uint64;
FoundPrimesCnt,
Line 3,304 ⟶ 4,228:
function InsertSievePrimes(PrimPos:NativeInt):NativeInt;
var
jdelta :NativeUINtNativeInt;
i,pr,loLmt : NativeUInt;
begin
i := 0;
Line 3,312 ⟶ 4,236:
i := maxPreSievePrimeNum;
pr :=0;
jloLmt := Uint64(SieveNum)*cSieveSize*(2-LastInsertedSievePrime*cSieveSize);
delta := loLmt-LastInsertedSievePrime;
with sievePrimes[PrimPos] do
Begin
pr := FoundPrimes[i]*2+1;
svdeltaPrime := pr+jdelta;
jdelta := pr;
end;
 
inc(PrimPos);
for i := i+1 to FoundPrimesCnt-1 do
Line 3,327 ⟶ 4,253:
Begin
pr := FoundPrimes[i]*2+1;
svdeltaPrime := (pr-jdelta);
jdelta := pr;
end;
inc(PrimPos);
end;
LastInsertedSievePrime :=Uint64(SieveNum)*cSieveSize*2 loLmt+pr;
result := PrimPos;
end;
Line 3,383 ⟶ 4,309:
SieveNum :=0;
CopyPreSieveInSieve;
//normal sieving of first block sieve
i := 1; // start with 3
repeat
Line 3,401 ⟶ 4,327:
CollectPrimes;
PrimPos := InsertSievePrimes(0);
//correct for SieveNum = 0
LastInsertedSievePrime := FoundPrimes[PrimPos]*2+1;
CalcSievePrimOfs(PrimPos);
 
Init0Sieve;
sieveOneBlock;
//now start collect with SieveNum = 1
IF PrimPos < High(sievePrimes) then
Begin
Init0Sieve;
//Erste Sieb nochmals, aber ohne Eintrag
sieveOneBlock;
repeat
sieveOneBlock;
CollectPrimes;
dec(SieveNum);
PrimPos := InsertSievePrimes(PrimPos);
inc(SieveNum);
until PrimPos > High(sievePrimes);
end;
Init0Sieve;
end;
Line 3,505 ⟶ 4,430:
procedure CollectPrimes;
//extract primes to FoundPrimes
 
//
var
pSieve : pbyte;
Line 3,511 ⟶ 4,436:
i,idx : NativeUint;
Begin
FoundPrimesOffset := SieveNum*(2*cSieveSize);
FoundPrimesIdx := 0;
pFound :=@FoundPrimes[0];
Line 3,538 ⟶ 4,463:
end;
 
procedure SieveOneBlock;inline;
begin
CopyPreSieveInSieve;
Line 3,546 ⟶ 4,471:
end;
 
procedure NextSieve;inline;
Begin
SieveOneBlock;
Line 3,561 ⟶ 4,486:
end;
 
function PosOfPrime: Uint64;inline;
Begin
result := FoundPrimesTotal-FoundPrimesCnt+FoundPrimesIdx;
end;
 
function TotalCountStartCount : Uint64 ;inline;
begin
result := FoundPrimesTotal-FoundPrimesCnt;
end;
 
function TotalCount :Uint64;inline;
begin
result := FoundPrimesTotal;
end;
 
function SieveSize :LongInt;inline;
Begin
result := 2*cSieveSize;
end;
 
function SieveStart:Uint64;inline;
Begin
result := (SieveNum-1)*2*cSieveSize;
end;
 
procedure InitPrime;inline;
Begin
Init0Sieve;
Line 3,592 ⟶ 4,522:
InitPrime;
end.
</syntaxhighlight>
{compiler: fpc/3.2.0/ppcx64 -Xs -O4 "%f"
50851378 in 1000079360 dauerte 529 ms
455052800 in 10000007168 dauerte 6297 ms
4118057696 in 100000071680 dauerte 93783 ms
}</lang>
 
;the test program:
<langsyntaxhighlight lang="pascal">
program test;
{$IFDEF FPC}
{$MODE objFPC}{$Optimization ON,ALL}
{$IFEND}
 
uses
primsieve;
 
var
icnt,p,lmt : NativeIntUint64;
cnt : Uint64;
Begin
lmt := 1000*1000*1000;
writeln('First 25 primes');
For ip := 1 to 25 do0;
while TotalCount < lmt do
write(Nextprime:3);
Begin
writeln;
NextSieve;
Writeln;
inc(p);
writeln('Primes betwenn 100 and 150');
If p AND (4096-1) = 0 then
repeat
write(p:8,TotalCount:15,#13);
i := NextPrime
end;
until i > 100;
cnt := StartCount;
repeat
write(i:4);
i := NextPrime;
until i>150;
writeln;
Writeln;
repeat
i := NextPrime
until i > 7700;
cnt := 0;
repeat
p := NextPrime;
inc(cnt);
until cnt i :>= NextPrimelmt;
writeln(cnt:14,p:14);
until i> 8000;
end.
writeln('between 7700 and 8000 are ',cnt,' primes');
{
Writeln;
10^n primecount
writeln(' i.th prime');
# 1 4
cnt := 10000;
# 2 25
repeat
# 3 while TotalCount < cnt do 168
# 4 NextSieve; 1229
# 5 repeat 9592
# 6 i := NextPrime; 78498
# 7 until PosOfPrime = cnt; 664579
# 8 5761455
writeln(cnt:10,i:12);
# 9 cnt := cnt*10; 50847534
# 10 455052511
until cnt >100*1000*1000;
# 11 4118054813
end.</lang>
# 12 37607912018
;output:
}</syntaxhighlight>
<pre>
{{out|@home}}
First 25 primes
<pre>//4.4 Ghz Ryzen 5600G fpc 3.3.1 -O3 -Xs
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
50847534 999999937
 
real 0m0,386s
Primes betwenn 100 and 150
455052511 9999999967
101 103 107 109 113 127 131 137 139 149
real 0m4,702s
 
4118054813 99999999977
between 7700 and 8000 are 30 primes
real 1m11,085s
 
37607912018 999999999989
i.th prime
real 19m1,195s
10000 104729
100000 1299709
1000000 15485863
10000000 179424673
100000000 2038074743
 
real 0m1,121s
</pre>
 
Line 3,671 ⟶ 4,585:
But i can hold all primes til 1e11 in 2.5 Gb memory.Test for isEmirp inserted.
32-bit is slow doing 64-Bit math.Using a dynamic array is slow too in NextPrime.
<langsyntaxhighlight lang="pascal">program emirp;
{$IFDEF FPC}
{$MODE DELPHI}
Line 4,325 ⟶ 5,239:
dgtCnt := 0;
until j >= MaxUpperLimit;
end.</langsyntaxhighlight>
;output:
<pre>//64-Bit
Line 4,372 ⟶ 5,286:
* <tt>primes</tt>, <tt>next_prime</tt>, <tt>prev_prime</tt>, <tt>forprimes</tt>, <tt>prime_iterator</tt>, <tt>prime_iterator_object</tt>, and primality tests will work for practically any size input. The [https://metacpan.org/pod/Math::Prime::Util::GMP Math::Prime::Uti::GMP] module is recommended for large inputs. With that module, these functions will work quickly for multi-thousand digit numbers.
 
<langsyntaxhighlight lang="perl">use Math::Prime::Util qw(nth_prime prime_count primes);
# Direct solutions.
# primes([start],end) returns an array reference with all primes in the range
Line 4,380 ⟶ 5,294:
say "Between 100 and 150: ", join(" ", @{primes(100,150)});
say prime_count(7700,8000), " primes between 7700 and 8000";
say "${_}th prime: ", nth_prime($_) for map { 10**$_ } 1..8;</langsyntaxhighlight>
{{out}}
<pre>First 20: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
Line 4,395 ⟶ 5,309:
 
There are many other ways, including <tt>prev_prime</tt> / <tt>next_prime</tt>, a simple iterator, an OO style iterator, a tied array, and a Pari-like <tt>forprimes</tt> construct. For example, the above example using the OO iterator:
<langsyntaxhighlight lang="perl">use Math::Prime::Util "prime_iterator_object";
my $it = prime_iterator_object;
say "First 20: ", join(" ", map { $it->iterate() } 1..20);
Line 4,406 ⟶ 5,320:
$c++ while $it->iterate() <= 8000;
say "$c primes between 7700 and 8000";
say "${_}th prime: ", $it->ith($_) for map { 10**$_ } 1..8;</langsyntaxhighlight>
Or using forprimes and a tied array:
<langsyntaxhighlight lang="perl">use Math::Prime::Util qw/forprimes/;
use Math::Prime::Util::PrimeArray;
tie my @primes, 'Math::Prime::Util::PrimeArray';
Line 4,420 ⟶ 5,334:
# The tied array tries to do the right thing -- sieve a window if it sees
# forward or backward iteration, and nth_prime if it looks like random access.
say "${_}th prime: ", $primes[$_-1] for map { 10**$_ } 1..8;</langsyntaxhighlight>
 
Example showing bigints:
<langsyntaxhighlight lang="perl">use bigint;
use Math::Prime::Util qw/forprimes prime_get_config/;
warn "No GMP, expect slow results\n" unless prime_get_config->{gmp};
my $n = 10**200;
forprimes { say $_-$n } $n,$n+1000;</langsyntaxhighlight>
{{out}}
<pre>
Line 4,450 ⟶ 5,364:
Some further discussion of this can be found on my talk page --[[User:Petelomax|Pete Lomax]] ([[User talk:Petelomax|talk]])
 
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>-- demo/rosetta/Extensible_prime_generator.exw
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence primes = {2,3,5,7}
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">free_console</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
atom sieved = 10
<span style="color: #004080;">sequence</span> <span style="color: #000000;">primes</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">}</span>
 
<span style="color: #004080;">atom</span> <span style="color: #000000;">sieved</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span>
procedure add_block()
integer N = min((sieved-1)*sieved,400000)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">add_block</span><span style="color: #0000FF;">()</span>
sequence sieve = repeat(1,N) -- sieve[i] is really i+sieved
<span style="color: #004080;">integer</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">((</span><span style="color: #000000;">sieved</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">sieved</span><span style="color: #0000FF;">,</span><span style="color: #000000;">400000</span><span style="color: #0000FF;">)</span>
for i=2 to length(primes) do -- (evens filtered on output)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sieve</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- sieve[i] is really i+sieved</span>
atom p = primes[i], p2 = p*p
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- (evens filtered on output)</span>
if p2>sieved+N then exit end if
<span style="color: #004080;">atom</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">p2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">*</span><span style="color: #000000;">p</span>
if p2<sieved+1 then
<span style="color: #008080;">if</span> <span style="color: #000000;">p2</span><span style="color: #0000FF;">></span><span style="color: #000000;">sieved</span><span style="color: #0000FF;">+</span><span style="color: #000000;">N</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
p2 += ceil((sieved+1-p2)/p)*p
<span style="color: #008080;">if</span> <span style="color: #000000;">p2</span><span style="color: #0000FF;"><</span><span style="color: #000000;">sieved</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">p2</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">ceil</span><span style="color: #0000FF;">((</span><span style="color: #000000;">sieved</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">p2</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">p</span>
p2 -= sieved
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if and_bits(p2,1)=0 then p2 += p end if
<span style="color: #000000;">p2</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">sieved</span>
-- if sieve[p2] then -- dang!
<span style="color: #008080;">if</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">p2</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">p</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
for k=p2 to N by p*2 do
<span style="color: #000080;font-style:italic;">-- if sieve[p2] then -- dang!</span>
sieve[k] = 0
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">p2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">by</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
-- end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #000080;font-style:italic;">-- end if</span>
for i=1 to N by 2 do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if sieve[i] then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
primes &= i+sieved
<span style="color: #008080;">if</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">primes</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">sieved</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
sieved += N
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #000000;">sieved</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">N</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
function is_prime2(integer n)
while sieved<n do
<span style="color: #008080;">function</span> <span style="color: #000000;">is_prime2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
add_block()
<span style="color: #008080;">while</span> <span style="color: #000000;">sieved</span><span style="color: #0000FF;"><</span><span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
end while
<span style="color: #000000;">add_block</span><span style="color: #0000FF;">()</span>
return binary_search(n,primes)>0
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">)></span><span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">20</span> <span style="color: #008080;">do</span> <span style="color: #000000;">add_block</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first 20 primes are: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">20</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">sieved</span><span style="color: #0000FF;"><</span><span style="color: #000000;">150</span> <span style="color: #008080;">do</span> <span style="color: #000000;">add_block</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">></span><span style="color: #000000;">150</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">p</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The primes between 100 and 150 are: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">7700</span> <span style="color: #008080;">to</span> <span style="color: #000000;">8000</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">is_prime2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">&=</span><span style="color: #000000;">i</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"There are %d primes between 7700 and 8000.\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">7</span><span style="color: #0000FF;">:</span><span style="color: #000000;">8</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">k</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">add_block</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The %,dth prime is : %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
atom t0 = time()
while length(primes)<20 do add_block() end while
printf(1,"The first 20 primes are: ") ?primes[1..20]
while sieved<150 do add_block() end while
sequence s = {}
for k=abs(binary_search(100,primes)) to length(primes) do
integer p = primes[k]
if p>150 then exit end if
s &= p
end for
printf(1,"The primes between 100 and 150 are: ") ?s
s = {}
for i=7700 to 8000 do
if is_prime2(i) then s&=i end if
end for
printf(1,"There are %d primes between 7700 and 8000.\n",length(s))
for i=1 to 8 do
integer k = power(10,i)
while length(primes)<k do
add_block()
end while
printf(1,"The %,dth prime is : %d\n",{k,primes[k]})
end for
?time()-t0</lang>
{{Out}}
<small>(Takes 11s to reach 1e7 under pwa/p2js)</small>
<pre>
The first 20 primes are: {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71}
Line 4,525 ⟶ 5,445:
27.578
</pre>
 
Using the builtins, for comparison only, output is identical though there is a marginal improvement in performance <small>(for reasons lost in the mists of time!)</small>:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first 20 primes are: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">get_primes</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)})</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">150</span><span style="color: #0000FF;">)[</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</span><span style="color: #0000FF;">))+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$]</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The primes between 100 and 150 are: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n7700to8000</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">8000</span><span style="color: #0000FF;">))-</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7700</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"There are %d primes between 7700 and 8000.\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n7700to8000</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">7</span><span style="color: #0000FF;">:</span><span style="color: #000000;">8</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The %,dth prime is : %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">get_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de prime? (N Lst)
(let S (sqrt N)
(for D Lst
Line 4,563 ⟶ 5,500:
N
"th prime: "
(last (take N)) ) )</langsyntaxhighlight>
{{out}}
<pre>First 20 primes: (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71)
Line 4,576 ⟶ 5,513:
===Faster version using a priority queue sieve and 2357 wheel===
This version runs about twice as quickly by using the method above to find small primes as a base for populating the priority queues required for the lazy sieve of Eratosthenes algorithm by Melissa O'Neil.
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(load "plcommon/pairing-heap.l") # Pairing heap from RC task "Priority Queue"
 
Line 4,644 ⟶ 5,581:
Q (* P P)
H (heap-insert (cons Q Wp P) H))))))))))
</syntaxhighlight>
</lang>
Driver code:
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(prin "The first 20 primes: ")
(do 20 (printsp (primes T)))
Line 4,675 ⟶ 5,612:
(prinl (align 9 (comma_fmt N)) " " (align 12 (comma_fmt (nthprime N)))))
(bye)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,691 ⟶ 5,628:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
DisableDebugger
Define StartTime.i=ElapsedMilliseconds()
Line 4,744 ⟶ 5,681:
Print(~"\nRuntime milliseconds: "+
Str(ElapsedMilliseconds()-StartTime))
Input()</langsyntaxhighlight>
{{out}}
<pre>First twenty: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
Line 4,755 ⟶ 5,692:
 
===Python: Croft spiral===
The Croft spiral sieve prime generator from the [[Prime_decomposition#Python:_Using_Croft_Spiral_sieve|Prime decomposition]] task is used which contains the line <langsyntaxhighlight lang="python">islice(count(7), 0, None, 2)</langsyntaxhighlight>
The call to <code>count(7)</code> is to a generator of integers that counts from 7 upwards with no upper limit set.<br>
The definition <code>croft</code> is a generator of primes and is used to generate as many primes as are asked for, in order.
 
<langsyntaxhighlight lang="python">from __future__ import print_function
from prime_decomposition import primes
from itertools import islice
Line 4,774 ⟶ 5,711:
print('The primes between 100 and 150:\n ', list(p_range(100, 150)))
print('The ''number'' of primes between 7,700 and 8,000:\n ', len(list(p_range(7700, 8000))))
print('The 10,000th prime:\n ', next(islice(primes(),10000-1, 10000)))</langsyntaxhighlight>
 
{{out}}
Line 4,789 ⟶ 5,726:
With more contemporary itertools use, 210-wheel incremental sieve with postponed primes processing and thus with radically reduced memory footprint which increases slower than square root of the number of primes produced:
 
<langsyntaxhighlight lang="python">def wsieve(): # ideone.com/mqO25A
wh11 = [ 2,4,2,4,6,2,6,4,2,4,6,6, 2,6,4,2,6,4,6,8,4,2,4,2,
4,8,6,4,6,2,4,6,2,6,6,4, 2,4,6,2,6,4,2,4,2,10,2,10 ]
cs = accumulate( chain( [11], cycle( wh11)))
yield( next( cs)) # cf. ideone.com/WFv4f
ps = wsieve() # codereview.stackexchange.com/q/92365/9064
p = next(ps) # 11 stackoverflow.com/q/30553925/849891
psq = p*p # 121
D = dict( zip( accumulate( chain( [0], wh11)), count(0) )) # start from
mults = {}
for c in cs:
if c in mults:
wheel = mults.pop(c)
elif c < psq:
yield c ; continue
continue
else: # c==psq: map (p*) (roll wh from p) = roll (wh*p) from (p*p)
x = [p*d for d in wh11]
i = D[ (p-11) % 210]
wheel = accumulate( chain( [psq+x[i]], cycle( x[i+1:] + x[:i+1])))
p = next(ps) ; psq = p*p
for m in wheel: psq = p*p
if notfor m in multswheel:
if not m in mults:
break
mults[m] = wheel
 
def primes():
yield from (2, 3, 5, 7)
yield from wsieve()
 
print( list( islice( primes(), 0, 20)))
print( list( takewhile( lambda x: x<150,
dropwhile( lambda x: x<100, primes()))))
print( len( list( takewhile( lambda x: x<8000,
dropwhile( lambda x: x<7700, primes())))))
print( listnext( islice( primes(), 10000-1, 10000))[0])</langsyntaxhighlight>
 
{{out}}
Line 4,836 ⟶ 5,775:
After a [[https://paddy3118.blogspot.com/2018/11/to-infinity-beyond.html?showComment=1541671062388#c8979782377032256564 blog entry]] on implementing a particular Haskell solution in Python.
 
<langsyntaxhighlight lang="python">from itertools import count, takewhile, islice
 
def prime_sieve():
Line 4,861 ⟶ 5,800:
sum(1 for x in takewhile(leq_8000, prime_sieve()) if x >= 7700))
print("Show the 10,000th prime.\n =",
next(islice(prime_sieve(), 10000-1, 10000)))</langsyntaxhighlight>
 
{{out}}
Line 4,884 ⟶ 5,823:
The link referenced in the source: [http://docs.racket-lang.org/math/number-theory.html?q=prime%3F#%28part._primes%29 <code>math/number-theory</code> module documentation]
 
<langsyntaxhighlight lang="scheme">#lang racket
;; Using the prime functions from:
(require math/number-theory)
Line 4,916 ⟶ 5,855:
2^256
(next-prime 2^256)
;; (Oh, and this is a 64-bit laptop, I left my 256-bit PC in the office.)</langsyntaxhighlight>
 
{{out}}
Line 4,934 ⟶ 5,873:
Build a lazy infinite list of primes using the Raku builtin is-prime method. ( A lazy list will not bother to calculate the values until they are actually used. ) That is the first line. If you choose to calculate the entire list, it is fairly certain that you will run out of process / system memory before you finish... (patience too probably) but there aren't really any other constraints. The is-prime builtin uses a Miller-Rabin primality test with 100 iterations, so while it is not 100% absolutely guaranteed that every number it flags as prime actually is, the chances that it is wrong are about 4<sup>-100</sup>. Much less than the chance that a cosmic ray will cause an error in your computers CPU. Everything after the first line is just display code for the various task requirements.
 
<syntaxhighlight lang="raku" perl6line>my @primes = lazy gather for 1 .. * { .take if .is-prime }
 
say "The first twenty primes:\n ", "[{@primes[^20].fmt("%d", ', ')}]";
Line 4,943 ⟶ 5,882:
sub between (@p, $l, $u) {
gather for @p { .take if $l < $_ < $u; last if $_ >= $u }
}</langsyntaxhighlight>
{{out}}
<pre>The first twenty primes:
Line 4,953 ⟶ 5,892:
The 10,000th prime:
104729</pre>
 
=={{header|Red}}==
<syntaxhighlight lang="red">
Red [Description: "Prime checker/generator/counter"]
 
context [
poke noprime: make bitset! 3 1 true
top: 2
 
noprimes: function [n [integer!] /extern top][
either top < n [
n: n + 100
r: 2
while [r * r <= n][
repeat q n / r - 1 [poke noprime q + 1 * r true]
until [not pick noprime r: r + 1]
]
self/top: n
][top]
]
 
set 'prime? func [
"Check whether number is prime or return required prime"
n [integer!]
/next "Return next closest prime to given number"
/last "Return last closest prime to given number, or number itself if prime"
/Nth "Return Nth prime"
][
noprimes case [
Nth [to integer! n * 12 ]
next [n + 100]
true [n]
]
case [
next [until [not noprime/(n: n + 1)] n]
last [while [noprime/:n][n: n - 1] n]
Nth [
cnt: i: 0
while [cnt < n][
until [not noprime/(i: i + 1)]
cnt: cnt + 1
]
i
]
true [not noprime/:n]
]
]
set 'primes function [
"Return (number of) primes in given range"
n [integer!]
/from "Start considering primes from `start`"
start "Default 1"
/list "First argument is interpreted as number of primes to list"
/count "Count primes from `start`"
][
start: any [start 1]
either list [
noprimes start + (n * 12)
][
set [start n] sort reduce [n start]
noprimes start + n
]
case [
list [
start: start - 1
collect [
loop n [
until [not noprime/(start: start + 1)]
keep start
]
]
]
count [
cnt: 0
repeat i n - start + 1 [
j: i - 1
if not noprime/(j + start) [cnt: cnt + 1]
]
cnt
]
true [
collect [
repeat i n - start + 1 [
j: i - 1
if not noprime/(j: j + start) [keep j]
]
]
]
]
]
]
</syntaxhighlight>
{{out}}<pre>
>> primes/list 20
== [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71]
>> primes/from 150 100
== [101 103 107 109 113 127 131 137 139 149]
>> primes/count/from 8000 7700
== 30
>> prime?/Nth 10000
== 104729
</pre>
 
=={{header|REXX}}==
Line 4,965 ⟶ 6,007:
 
This REXX program uses some hardcoded divisions. &nbsp; While the hardcoded divisions are not necessary, they do speed up the division process in validating if a number is prime (or not), &nbsp; and the hardcoded divisions bypass the repetitive tests to see if a (low) prime that is being used for division is greater than the number being divided (tested). &nbsp; The hardcoded divisions also bypass (or, at least, postpones) the computation of the integer square roots.
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays primes using an extendible prime number generator*/
parse arg f .; if f=='' then f= 20 /*allow specifying number for 1 ──► F.*/
_i= ' (inclusive) '; _b= 'between '; _tnp= 'the number of primes' _b; _tn= 'the primes'
Line 5,014 ⟶ 6,056:
L= 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
do #=1 for words(L); p= word(L, #); @.#= p; !.p=1; end /*#*/
#= # - 1; @.lowP= #; return /*#: # primes; @.lowP: start of ÷ */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 5,027 ⟶ 6,069:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "first twenty primes : "
i = 1
Line 5,066 ⟶ 6,108:
next
return true
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,077 ⟶ 6,119:
=={{header|Ruby}}==
The prime library behaves like an enumerator. It has an "each" method, which takes an upper bound as argument. This argument is nil by default, which means no upper bound.
<langsyntaxhighlight lang="ruby">require "prime"
 
puts Prime.take(20).join(", ")
puts Prime.each(150).drop_while{|pr| pr < 100}.join(", ")
puts Prime.each(8000).drop_while{|pr| pr < 7700}.count
puts Prime.take(10_000).last</langsyntaxhighlight>
{{out}}
<pre>
Line 5,095 ⟶ 6,137:
Uses the code from [[Sieve_of_Eratosthenes#Unbounded_Page-Segmented_bit-packed_odds-only_version_with_Iterator]]; copy that code into a file named <code>src/pagesieve.rs</code> and prepend <code>pub</code> to all function declarations used in this code (<code>count_primes_paged</code> and <code>primes_paged</code>).
 
<langsyntaxhighlight lang="rust">mod pagesieve;
 
use pagesieve::{count_primes_paged, primes_paged};
Line 5,110 ⟶ 6,152:
// rust enumerations are zero base, so need to subtract 1!!!
println!("The 10,000th prime is {}", primes_paged().nth(10_000 - 1).unwrap());
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,125 ⟶ 6,167:
cannot be used, because it needs a limit. Instead the function getPrime is used.
GetPrime generates all primes in sequence.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func boolean: isPrime (in integer: number) is func
Line 5,188 ⟶ 6,230:
until primeNum = 9999; # discard up to and including the 9,999 prime!
writeln("The 10,000th prime: " <& getPrime);
end func;</langsyntaxhighlight>
 
{{out}}
Line 5,199 ⟶ 6,241:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">say ("First 20: ", 20.nth_prime.primes.join(' '))
say ("Between 100 and 150: ", primes(100,150).join(' '))
say (prime_count(7700,8000), " primes between 7700 and 8000")
say ("10,000th prime: ", nth_prime(10_000))</langsyntaxhighlight>
{{out}}
<pre>
Line 5,214 ⟶ 6,256:
 
The [[Sieve_of_Eratosthenes#Unbounded_.28Odds-Only.29_Versions]] Swift examples contain several versions that are Extensible Prime Generators using the Sieve of Eratosthenese. One of the simplest is the Hashed Dictionary, reproduced here as follows:
<langsyntaxhighlight lang="swift">import Foundation
 
func soeDictOdds() -> UnfoldSequence<Int, Int> {
Line 5,268 ⟶ 6,310:
 
print(answr)
print(String(format: "This test took %.3f milliseconds.", elpsd * 1000))</langsyntaxhighlight>
{{output}}
<pre>The first 20 primes are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
Line 5,285 ⟶ 6,327:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# An iterative version of the Sieve of Eratosthenes.
Line 5,338 ⟶ 6,380:
}
puts prime10000=$prime
rename $p {}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,348 ⟶ 6,390:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 5,421 ⟶ 6,463:
ReDim Preserve L(c)
ListPrimes = L
End Function</langsyntaxhighlight>
{{out}}
<pre>For N = 133 218 295, execution time : 9,422 s, 7 550 284 primes numbers.
Line 5,437 ⟶ 6,479:
The last prime I could find is the : 7 550 283th, Value : 133 218 289</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
'uses variant booleans for the sieve, so 16 bytes per bit, a little wasteful!
 
Option Explicit
 
Sub sieveit(maxi) 'increases sieve size up to maxi and sieves the added part
Dim lasttop,a,b,c,i,j
lasttop=UBound(primes)
If maxi>lasttop Then
ReDim preserve primes(maxi)
print vbcrlf &"(sieving from " & lasttop & " up to " & maxi &")"& vbCrLf
For i=lasttop+1 To maxi
primes(i)=True
next
For i=2 To Int(Sqr(lasttop))
If primes(i)=True Then
a=lasttop\i
b=maxi\i
c= i*a
For j=a To b
primes(c)=False
c=c+i
Next
End if
Next
For i=Int(Sqr(lasttop)) To Int(Sqr(maxi))
If primes(i)=True Then
c=i*i
While c<=maxi
primes(c)=False
c=c+i
wend
End if
next
End if
End Sub
 
function nth(n) 'returns the nth prime (sieves if needed)
Dim cnt,i,m
m=Int(n *(Log(n)+Log(Log(n))))
If m>UBound(primes) Then sieveit (m)
i=1
Do
i=i+1
If primes(i) Then cnt=cnt+1
Loop until cnt=n
nth=i
End function
 
Sub printprimes (x1, x2,p) ' counts and prints (if p=true) primes between x1 and x2 (sieves if needed)
Dim lasttop,n,cnt,i
If x2> UBound(primes) Then sieveit(x2)
print "primes in range " & x1 & " To " & x2 & vbCrLf
cnt=0
For i=x1 To x2
If primes(i) Then
If p Then print i & vbTab
cnt=cnt+1
End if
next
print vbCrLf & "Count: " & cnt
End Sub
 
 
Sub print(s):
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
 
 
 
' main program-------------------------------------------
Dim n
' initialization of the array of booleans
reDim Primes(2)
primes(0) = False
Primes(1) = False
Primes(2) = True
 
'Show the first twenty primes.
n=nth(20)
printprimes 1,n,1
 
'Show the primes between 100 and 150.
printprimes 100,150,1
 
'Show the number of primes between 7,700 and 8,000.
printprimes 7700,8000,0
 
'Show the 10,000th prime.
n= nth(10000)
print n & " is the " & 10000 & "th prime"
</syntaxhighlight>
{{out}}
<small>
<pre>
(sieving from 2 up to 81)
 
primes in range 1 To 71
 
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
 
Count: 20
 
(sieving from 81 up to 150)
 
primes in range 100 To 150
 
101
103
107
109
113
127
131
137
139
149
 
Count: 10
 
(sieving from 150 up to 8000)
 
primes in range 7700 To 8000
 
 
Count: 30
 
(sieving from 8000 up to 114306)
 
104729 is the 10000th prime
</pre>
</small>
=={{header|Wren}}==
This uses a larger wheel than the sieve in the Wren-math module and is a bit faster if one is sieving beyond about 10^7.
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var primeSieve = Fn.new { |limit|
Line 5,499 ⟶ 6,696:
Fmt.print("\nThe 10,000th prime is: $,d", primes[9999])
Fmt.print("\nThe 100,000th prime is: $,d", primes[99999])
Fmt.print("\nThe 1,000,000th prime is: $,d", primes[999999])</langsyntaxhighlight>
 
{{out}}
Line 5,523 ⟶ 6,720:
 
Implementation:
<syntaxhighlight lang="zig">
<lang Zig>
const std = @import("std");
const builtin = std.builtin;
Line 5,676 ⟶ 6,873:
};
}
</syntaxhighlight>
</lang>
Driver code:
<syntaxhighlight lang="zig">
<lang Zig>
const std = @import("std");
const sieve = @import("sieve.zig");
Line 5,684 ⟶ 6,881:
const heap = std.heap;
 
const stdout = std.io.getStdOut().outStreamwriter();
pub fn main() !void {
try part1();
Line 5,728 ⟶ 6,925:
try stdout.print("There are {} primes between 7700 and 8000.\n", .{count});
}
 
// exercize 3: find big primes
fn part3() !void {
Line 5,747 ⟶ 6,944:
}
}
 
</lang>
</syntaxhighlight>
{{Out}}
<pre>
The first 20 primes: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
The primes between 100 and 150: 101 103 107 109 113 127 131 137 139 149
There are 30 primes between 7700 and 8000.
The 10th prime is 29
The 100th prime is 541
The 1000th prime is 7919
The 10000th prime is 104729
The 100000th prime is 1299709
The 1000000th prime is 15485863
The 10000000th prime is 179424673
The 100000000th prime is 2038074743
</pre>
=== Alternative version based on "Two Compact Incremental Prime Sieves" by Jonathon P. Sorenson.===
Like the version based on the O'Neil sieve, this version also uses metaprogramming, this time to properly calculate the sizes of the buckets required by the algorithm (the sieve is implemented as an array of buckets, each bucket containing a list of the unique prime factors of that entry.) It's quite memory efficient for a u32 and below (16 bytes per bucket), though it is not memory efficient for larger sieves. For example, a u36 requires a bucket size of 36 bytes.)
 
As with the O'Neil sieve, this version thus represents a spectrum of fixed or unbounded generators. PrimeGen(u32) (or PrimeGen(u64)) can be used as an unbounded sieve, whereas a PrimeGen(u10) represents a fixed sieve for all primes < 1024.
 
Since this version uses an array (O(1)) rather than an O(log n) priority queue, it is significantly faster. On my laptop, sieving up to 100,000,000 primes takes 2:18 seconds for the O'Neil sieve and 52 seconds for the Sorenson.
<syntaxhighlight lang="zig">
// Since in the common case (primes < 2^32 - 1), the stack only needs to be 8 16-bit words long
// (only twice the size of a pointer) the required stacks are stored in each cell, rather
// than using an indirection (e.g. linked list of integer cells)
//
const std = @import("std");
const builtin = std.builtin;
const meta = std.meta;
const mem = std.mem;
 
fn assertInt(comptime T: type) builtin.TypeInfo.Int {
const Signedness = builtin.Signedness;
if (@typeInfo(T) != .Int)
@compileError("data type must be an integer.");
const int = @typeInfo(T).Int;
if (int.signedness == Signedness.signed or int.bits % 2 == 1 or int.bits < 4 or int.bits > 64)
@compileError("type must be an unsigned integer with even bit size (of at least 4 bits).");
return int;
}
 
// given a type, return the maximum stack size required by the algorthm.
fn listSize(comptime T: type) usize {
_ = assertInt(T);
const primes = [_]u6{
2, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53,
};
// Find the first primorial that will overflow type T.
// the size of the list is the primorial index minus one,
// since the sieve doesn't include 2.
//
var i: usize = 0;
var pi: T = 1;
while (!@mulWithOverflow(T, pi, primes[i], &pi))
i += 1;
return i - 1;
}
 
fn sqrtType(comptime T: type) type {
const t = assertInt(T);
return meta.Int(.unsigned, t.bits / 2);
}
 
// stack type (actually just an array list)
fn arrayList(comptime Int: type) type {
return [listSize(Int)]sqrtType(Int);
}
 
// given an upper bound, max, return the most restrictive sieving data type.
pub fn autoSieveType(comptime max: u64) type {
if (max == 0)
@compileError("The maximum sieving size must be non-zero.");
var bit_len = 64 - @clz(u64, max);
if (max & (max - 1) == 0) // power of two
bit_len -= 1;
if (bit_len % 2 == 1)
bit_len += 1;
if (bit_len < 4)
bit_len = 4;
return meta.Int(.unsigned, bit_len);
}
 
test "type meta functions" {
const expect = std.testing.expect;
try expect(sqrtType(u20) == u10);
try expect(autoSieveType(8000) == u14);
try expect(autoSieveType(9000) == u14);
try expect(autoSieveType(16384) == u14);
try expect(autoSieveType(16385) == u16);
try expect(autoSieveType(32768) == u16);
try expect(autoSieveType(1000) == u10);
try expect(autoSieveType(10) == u4);
try expect(autoSieveType(4) == u4);
try expect(autoSieveType(std.math.maxInt(u32)) == u32);
try expect(listSize(u64) == 14);
try expect(listSize(u32) == 8);
try expect(@sizeOf(arrayList(u32)) == 16);
try expect(@sizeOf(arrayList(u36)) == 36);
try expect(@sizeOf(arrayList(u64)) == 56);
}
 
pub fn PrimeGen(comptime Int: type) type {
_ = assertInt(Int);
return struct {
const Self = @This();
const Sieve = std.ArrayList(arrayList(Int));
 
sieve: Sieve,
count: usize,
candidate: Int,
rt: sqrtType(Int),
sq: Int,
pos: usize,
 
// grow the sieve by a comptime fixed amount
fn growBy(self: *Self, comptime n: usize) !void {
var chunk: [n]arrayList(Int) = undefined;
for (chunk) |*a|
mem.set(sqrtType(Int), a, 0);
try self.sieve.appendSlice(&chunk);
}
 
// add a known prime number to the sieve at postion k
fn add(self: *Self, p: sqrtType(Int), k: usize) void {
for (self.sieve.items[k]) |*x|
if (x.* == 0) {
x.* = p;
return;
};
// each bucket is precalculated for the max size.
// If we get here, there's been a mistake somewhere.
unreachable;
}
 
pub fn init(alloc: *mem.Allocator) Self {
return Self{
.count = 0,
.sieve = Sieve.init(alloc),
.candidate = 3,
.rt = 3,
.sq = 9,
.pos = 0,
};
}
 
pub fn deinit(self: *Self) void {
self.sieve.deinit();
}
 
pub fn next(self: *Self) !?Int {
self.count += 1;
if (self.count == 1) {
try self.growBy(1); // prepare sieve
return 2;
} else {
var is_prime = false;
while (!is_prime) {
is_prime = true;
// Step 1: check the list at self.pos; if there are divisors then
// the candidate is not prime. Move each divisor to its next multiple
// in the sieve.
//
if (self.sieve.items[self.pos][0] != 0) {
is_prime = false;
for (self.sieve.items[self.pos]) |*x| {
const p = x.*;
x.* = 0;
if (p == 0)
break;
self.add(p, (p + self.pos) % self.sieve.items.len);
}
}
// Step 2: If we've hit the next perfect square, and we thought the number
// was prime from step 1, note that it wasn't prime but rather was a non p-smooth
// number. Add the square root to the sieve. In any case, look ahead to the next
// square number.
//
if (self.candidate == self.sq) {
if (is_prime) {
is_prime = false;
self.add(self.rt, (self.pos + self.rt) % self.sieve.items.len);
}
// advance to the next root; if doing so would cause overflow then just ignore it,
// since we'll never see the next square.
//
var rt: sqrtType(Int) = undefined;
if (!@addWithOverflow(sqrtType(Int), self.rt, 2, &rt)) {
self.rt = rt;
self.sq = @as(Int, rt) * rt;
}
}
// advance the iterator; Note if we overflow, the candidate cannot be prime
// since the bit count must be even and all integers of the form 2^n - 1 with
// even n (except 2) are composite.
//
if (@addWithOverflow(Int, self.candidate, 2, &self.candidate)) {
std.debug.assert(!is_prime);
return null;
}
self.pos += 1;
if (self.pos == self.sieve.items.len) {
// expand the array by 2 to maintain the invariant: sieve.items.len > √candidate
try self.growBy(2);
self.pos = 0;
}
}
return self.candidate - 2;
}
}
};
}
</syntaxhighlight>
The driver code is the same with this version, since the interface is unchanged from the O'Neil sieve.
{{Out}}
<pre>
Line 5,764 ⟶ 7,175:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">// http://stackoverflow.com/revisions/10733621/4
 
fcn postponed_sieve(){ # postponed sieve, by Will Ness
Line 5,793 ⟶ 7,204:
while(D.holds(x)){ x += s } # increment by the given step
D[x] = s;
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">primes:=Utils.Generator(postponed_sieve);
primes.walk(20).println(); // first 20 primes
Line 5,809 ⟶ 7,220:
 
// or to carry on until the 100,000th:
primes.pump(Void,'wrap(p){ primes.n<=0d100_000 and p or Void.Stop }).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 5,821 ⟶ 7,232:
Using GMP (GNU Multiple Precision Arithmetic Library, probabilistic primes), this is a direct drop in for the above:
{{libheader|GMP}}
<langsyntaxhighlight lang="zkl">var [const] BN=Import.lib("zklBigNum"); // libGMP
bigPrimes:=Walker(fcn(p){ p.nextPrime().copy(); }.fp(BN(1)));</langsyntaxhighlight>
For example:
<langsyntaxhighlight lang="zkl">bigPrimes.walk(20).println(); // first 20 primes
bigPrimes.pump(Void,'wrap(p){ bigPrimes.n<=0d10_000 and p or Void.Stop }).println();</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits