Piprimes: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Sidef)
m (→‎{{header|Wren}}: Minor tidy)
 
(20 intermediate revisions by 15 users not shown)
Line 11: Line 11:
:* &nbsp; the OEIS entry: &nbsp; [http://oeis.org/A000720 A0000720 pi(n), the number of primes <= n. Sometimes called PrimePi(n)...].
:* &nbsp; the OEIS entry: &nbsp; [http://oeis.org/A000720 A0000720 pi(n), the number of primes <= n. Sometimes called PrimePi(n)...].
<br><br>
<br><br>

=={{header|11l}}==
{{trans|Nim}}

<syntaxhighlight lang="11l">F is_prime(n)
I n == 2
R 1B
I n < 2 | n % 2 == 0
R 0B
L(i) (3 .. Int(sqrt(n))).step(2)
I n % i == 0
R 0B
R 1B

V pi = 0
V n = 1
L
print(‘#2’.format(pi), end' I n % 10 == 0 {"\n"} E ‘ ’)
n++
I is_prime(n)
pi++
I pi == 22
L.break
print()</syntaxhighlight>

{{out}}
<pre>
0 1 2 2 3 3 4 4 4 4
5 5 6 6 6 6 7 7 8 8
8 8 9 9 9 9 9 9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21
</pre>

=={{header|Action!}}==
{{libheader|Action! Sieve of Eratosthenes}}
<syntaxhighlight lang="action!">INCLUDE "H6:SIEVE.ACT"

PROC Main()
DEFINE MAX="100"
BYTE ARRAY primes(MAX+1)
INT n=[0],p=[1]

Put(125) PutE() ;clear the screen
Sieve(primes,MAX+1)
WHILE n<22
DO
PrintB(n) Put(32)
p==+1
IF primes(p) THEN
n==+1
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Piprimes.png Screenshot from Atari 8-bit computer]
<pre>
0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14
14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21
</pre>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-primes}}
<lang algol68>BEGIN # Show some values of pi(n) - the number of priems <= n #
<syntaxhighlight lang="algol68">BEGIN # Show some values of pi(n) - the number of priems <= n #
# reurns a sieve of primes up to n #
PROC prime sieve = ( INT n )[]BOOL:
BEGIN
[ 1 : n ]BOOL p;
p[ 1 ] := FALSE; p[ 2 ] := TRUE;
FOR i FROM 3 BY 2 TO n DO p[ i ] := TRUE OD;
FOR i FROM 4 BY 2 TO n DO p[ i ] := FALSE OD;
FOR i FROM 3 BY 2 TO ENTIER sqrt( n ) DO
IF p[ i ] THEN FOR s FROM i * i BY i + i TO n DO p[ s ] := FALSE OD FI
OD;
p
END # prime sieve # ;
# show pi(n) for n up to 21 #
# show pi(n) for n up to 21 #
INT max number = 100; # guess of how large the primes we need are #
INT max prime = 100; # guess of how large the primes we need are #
INT max pi = 21;
INT max pi = 21;
PR read "primes.incl.a68" PR
[]BOOL prime = prime sieve( max number );
[]BOOL prime = PRIMESIEVE max prime;
INT pi := 0;
INT pi := 0;
FOR i TO max number
FOR i TO UPB prime
WHILE IF prime[ i ] THEN pi +:= 1 FI;
WHILE IF prime[ i ] THEN pi +:= 1 FI;
pi <= max pi
pi <= max pi
Line 38: Line 91:
IF i MOD 10 = 0 THEN print( ( newline ) ) FI
IF i MOD 10 = 0 THEN print( ( newline ) ) FI
OD
OD
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 50: Line 103:
20 20 21 21 21 21 21 21
20 20 21 21 21 21 21 21
</pre>
</pre>

=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>primes: select 2..1000 => prime?
<syntaxhighlight lang="rebol">primes: select 2..1000 => prime?
piprimes: function [n] -> size select primes 'z [z =< n]
piprimes: function [n] -> size select primes 'z [z =< n]


loop split.every: 10 select map 1..100 => piprimes => [& < 22] 'a ->
loop split.every: 10 select map 1..100 => piprimes => [& < 22] 'a ->
print map a => [pad to :string & 3]</lang>
print map a => [pad to :string & 3]</syntaxhighlight>


{{out}}
{{out}}
Line 70: Line 124:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PIPRIMES.AWK
# syntax: GAWK -f PIPRIMES.AWK
# converted from FreeBASIC
# converted from FreeBASIC
Line 97: Line 151:
return(1)
return(1)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 112: Line 166:


=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">function isPrime(v)
if v < 2 then return False
if v mod 2 = 0 then return v = 2
if v mod 3 = 0 then return v = 3
d = 5
while d * d <= v
if v mod d = 0 then return False else d += 2
end while
return True
end function

running = 0 : curr = 0 : limite = 22
while True
curr += 1
if isPrime(curr) then running += 1
if running = limite then exit while
print running; " ";
end while
end</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>


==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
<lang freebasic>#define UPTO 22
<syntaxhighlight lang="freebasic">#define UPTO 22
#include "isprime.bas"
#include "isprime.bas"


Line 125: Line 204:
loop
loop
print : end
print : end
</syntaxhighlight>
</lang>
{{out}}<pre>
{{out}}<pre>
0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21</pre>
0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21</pre>


==={{header|Tiny BASIC}}===
==={{header|Tiny BASIC}}===
<lang tinybasic> LET N = 0
<syntaxhighlight lang="tinybasic"> LET N = 0
LET P = 0
LET P = 0
10 IF N = 22 THEN END
10 IF N = 22 THEN END
Line 145: Line 224:
LET I = I + 1
LET I = I + 1
IF I*I <= P THEN GOTO 110
IF I*I <= P THEN GOTO 110
RETURN</lang>
RETURN</syntaxhighlight>

==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">sub isPrime(v)
if v < 2 then return False : fi
if mod(v, 2) = 0 then return v = 2 : fi
if mod(v, 3) = 0 then return v = 3 : fi
d = 5
while d * d <= v
if mod(v, d) = 0 then return False else d = d + 2 : fi
wend
return True
end sub

running = 0 : curr = 0 : limite = 22
do
curr = curr + 1
if isPrime(curr) then running = running + 1 : fi
if running = limite break
print running using "##", " ";
loop
end</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>



=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 168: Line 274:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 175: Line 281:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


sub isPrime(n: uint8): (r: uint8) is
sub isPrime(n: uint8): (r: uint8) is
Line 205: Line 311:
end loop;
end loop;
print_nl();
print_nl();
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 217: Line 323:
20 20 21 21 21 21 21 21
20 20 21 21 21 21 21 21
</pre>
</pre>

=={{header|Dart}}==
{{trans|C}}
<syntaxhighlight lang="dart">import 'dart:math';
import 'dart:io';

void main() {
int n = 0, p = 1;
while (n < 22) {
stdout.write("$n ");
++p;
if (isPrime(p)) ++n;
}
}

bool isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
for (int i = 2; i <= sqrt(n); ++i) {
if (n % i == 0) return false;
}
return true;
}</syntaxhighlight>

=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}


<syntaxhighlight lang="Delphi">
function IsPrime(N: int64): boolean;
{Fast, optimised prime test}
var I,Stop: int64;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
begin
I:=5;
Stop:=Trunc(sqrt(N+0.0));
Result:=False;
while I<=Stop do
begin
if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
Inc(I,6);
end;
Result:=True;
end;
end;





procedure ShowPiprimes(Memo: TMemo);
var N, P, Cnt: integer;
var S: string;
begin
N:= 0;
P:= 1;
Cnt:= 0;
S:='';
repeat
begin
S:=S+Format('%3D',[N]);
Inc(Cnt);
if (Cnt mod 10)=0 then S:=S+CRLF;
Inc(P);
if IsPrime(P) then N:= N+1;
end
until N >= 22;
Memo.Lines.Add(S);
end;

</syntaxhighlight>
{{out}}
<pre>
0 1 2 2 3 3 4 4 4 4
5 5 6 6 6 6 7 7 8 8
8 8 9 9 9 9 9 9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21
Elapsed Time: 1.328 ms.

</pre>



=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
<syntaxhighlight lang="fsharp">
// PiPrimes: Nigel Galloway. April 5th., 2021
// PiPrimes: Nigel Galloway. April 5th., 2021
let fN=let i=primes32() in Seq.unfold(fun(n,g,l)->Some(l,if n=g then (n+1,Seq.head i,l+1) else (n+1,g,l)))(1,Seq.head i,0)
let fN=let i=primes32() in Seq.unfold(fun(n,g,l)->Some(l,if n=g then (n+1,Seq.head i,l+1) else (n+1,g,l)))(1,Seq.head i,0)
fN|>Seq.takeWhile((>)22)|>Seq.chunkBySize 20|>Seq.iter(fun n->Array.iter(printf "%2d ") n; printfn "")
fN|>Seq.takeWhile((>)22)|>Seq.chunkBySize 20|>Seq.iter(fun n->Array.iter(printf "%2d ") n; printfn "")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 235: Line 430:
=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.99 2021-02-05}}
{{works with|Factor|0.99 2021-02-05}}
<lang factor>USING: formatting grouping io lists math.primes
<syntaxhighlight lang="factor">USING: formatting grouping io lists math.primes
math.primes.lists math.ranges math.statistics sequences ;
math.primes.lists math.ranges math.statistics sequences ;


21 lprimes lnth [1,b) [ prime? ] cum-count
21 lprimes lnth [1,b) [ prime? ] cum-count
10 group [ [ "%2d " printf ] each nl ] each</lang>
10 group [ [ "%2d " printf ] each nl ] each</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 253: Line 448:


=={{header|Fermat}}==
=={{header|Fermat}}==
<lang fermat>n:=0; p:=0
<syntaxhighlight lang="fermat">n:=0; p:=0
while n<22 do !n;!' ';p:=p+1;if Isprime(p)=1 then n:=n+1; fi; od</lang>
while n<22 do !n;!' ';p:=p+1;if Isprime(p)=1 then n:=n+1; fi; od</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21</pre>
0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21</pre>


=={{header|FOCAL}}==
=={{header|FOCAL}}==
<lang FOCAL>01.10 S C=0
<syntaxhighlight lang="focal">01.10 S C=0
01.20 S N=1
01.20 S N=1
01.30 T %3,C
01.30 T %3,C
Line 272: Line 467:
02.30 I (I*I-N-1)2.4;S A=1;R
02.30 I (I*I-N-1)2.4;S A=1;R
02.40 S A=N/I
02.40 S A=N/I
02.50 I (FITR(A)-A)2.2;S A=0</lang>
02.50 I (FITR(A)-A)2.2;S A=0</syntaxhighlight>
{{out}}
{{out}}
<pre>= 0= 1= 2= 2= 3= 3= 4= 4= 4= 4= 5= 5= 6= 6= 6= 6
<pre>= 0= 1= 2= 2= 3= 3= 4= 4= 4= 4= 5= 5= 6= 6= 6= 6
Line 279: Line 474:
= 15= 15= 15= 15= 16= 16= 16= 16= 16= 16= 17= 17= 18= 18= 18= 18
= 15= 15= 15= 15= 16= 16= 16= 16= 16= 16= 17= 17= 18= 18= 18= 18
= 18= 18= 19= 19= 19= 19= 20= 20= 21= 21= 21= 21= 21= 21</pre>
= 18= 18= 19= 19= 19= 19= 20= 20= 21= 21= 21= 21= 21= 21</pre>


=={{header|FutureBasic}}==
<syntaxhighlight futurebasic"j">
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


local fn Piprimes( limit as NSUInteger )
NSUInteger n = 0, p = 1
printf @"Piprimes from 1 through %lu:\n", limit
while ( n < limit )
printf @"%2lu \b", n
if p mod 10 == 0 then print
p++
if ( fn IsPrime(p) ) then n++
wend
end fn

fn Piprimes( 22 )

HandleEvents
</syntaxhighlight>
{{output}}}
<pre>
Piprimes from 1 through 22:

0 1 2 2 3 3 4 4 4 4
5 5 6 6 6 6 7 7 8 8
8 8 9 9 9 9 9 9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21
</pre>


=={{header|J}}==
=={{header|J}}==
<lang J>}.@(>:@i.&.p:) 21</lang>
<syntaxhighlight lang="j">}.@(>:@i.&.p:) 21</syntaxhighlight>
{{out}}
{{out}}
<pre>0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21</pre>
<pre>0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21</pre>
Line 288: Line 529:
{{trans|Wren}}
{{trans|Wren}}
{{libheader|Go-rcu}}
{{libheader|Go-rcu}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 320: Line 561:
}
}
fmt.Printf("\n\nHighest n for this range = %d.\n", len(pi))
fmt.Printf("\n\nHighest n for this range = %d.\n", len(pi))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 335: Line 576:


Highest n for this range = 78.
Highest n for this range = 78.
</pre>

=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''

This entry uses an approach based on streams of unbounded length;
this has the advantage that no guessing or smarts is needed, either
to provide a solution for the given bound (pi(n)<22) or any such bound.

For a suitable implementation of `is_prime` see e.g. [[Erd%C5%91s-primes#jq]].

'''Preliminaries'''
<syntaxhighlight lang="jq">def count(s): reduce s as $x (null; .+1);

def emit_until(cond; stream):
label $out | stream | if cond then break $out else . end;

def next_prime:
if . == 2 then 3
else first(range(.+2; infinite; 2) | select(is_prime))
end;</syntaxhighlight>
'''The task'''
<syntaxhighlight lang="jq"># Generate pi($n) for $n > 0
def pi_primes:
foreach range(1; infinite) as $i ({n:0, np: 2}; # n counts, np is the next prime
if $i < .np then .
elif $i == .np then .n += 1 | .np |= next_prime
else .
end;
.n);

emit_until(. >= 22; pi_primes)</syntaxhighlight>
{{out}}
<pre>
0
1
2
2
3
3
4
4
4
4
...
19
19
19
19
20
20
21
21
21
21
21
21
</pre>
</pre>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>using Primes
<syntaxhighlight lang="julia">using Primes


function listpiprimes(maxpi)
function listpiprimes(maxpi)
Line 350: Line 649:


listpiprimes(22)
listpiprimes(22)
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
0 1 2 2 3 3 4 4 4 4
0 1 2 2 3 3 4 4 4 4
Line 361: Line 660:
20 20 21 21 21 21 21 21
20 20 21 21 21 21 21 21
</pre>
</pre>

=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">pi = PrimePi /@ Range[Prime[22] - 1];
Multicolumn[pi, {Automatic, 10}, Appearance -> "Horizontal"]</syntaxhighlight>
{{out}}
<pre>0 1 2 2 3 3 4 4 4 4
5 5 6 6 6 6 7 7 8 8
8 8 9 9 9 9 9 9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21 </pre>


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import strutils
<syntaxhighlight lang="nim">import strutils


func isPrime(n: Natural): bool =
func isPrime(n: Natural): bool =
Line 385: Line 697:
inc pi
inc pi
if pi == 22: break
if pi == 22: break
echo()</lang>
echo()</syntaxhighlight>




Line 399: Line 711:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>n=0; p=0
<syntaxhighlight lang="parigp">n = 1;
while( primepi( n ) < 22,
while(n<22, print(n); if(isprime(p),n=n+1);p=p+1)</lang>
printf( "%3d", primepi(n) );
if( n++ % 10 == 1,
print()) )</syntaxhighlight>
{{out}}
0 1 2 2 3 3 4 4 4 4
5 5 6 6 6 6 7 7 8 8
8 8 9 9 9 9 9 9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21


=={{header|Perl}}==
=={{header|Perl}}==
{{libheader|ntheory}}
{{libheader|ntheory}}
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use feature 'state';
use feature 'state';
Line 410: Line 734:


my @pi = map { state $pi = 0; $pi += is_prime $_ ? 1 : 0 } 1..1e4;
my @pi = map { state $pi = 0; $pi += is_prime $_ ? 1 : 0 } 1..1e4;
do { print shift(@pi) . ' ' } until $pi[0] >= 22;</lang>
do { print shift(@pi) . ' ' } until $pi[0] >= 22;</syntaxhighlight>
{{out}}
{{out}}
<pre>0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21</pre>
<pre>0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21</pre>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ix</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: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ix</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: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
Line 429: Line 753:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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;">"pi[1..%d]:\n%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</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;">"pi[1..%d]:\n%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 442: Line 766:
20 20 21 21 21 21 21 21
20 20 21 21 21 21 21 21
</pre>
</pre>

=={{header|Quackery}}==

<code>isprime</code> is defined at [[Primality by trial division#Quackery]].

<syntaxhighlight lang="quackery"> [ 0 swap
1 - times
[ i 1+ isprime + ] ] is pi ( n --> n )

2 [ dup pi dup 22 < while
echo sp 1+ again ]
2drop</syntaxhighlight>

{{out}}

<pre>0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21</pre>


=={{header|Raku}}==
=={{header|Raku}}==
<lang perl6>my @pi = (1..*).map: { state $pi = 0; $pi += .is-prime };
<syntaxhighlight lang="raku" line>my @pi = (1..*).map: { state $pi = 0; $pi += .is-prime };


say @pi[^(@pi.first: * >= 22, :k)].batch(10)».fmt('%2d').join: "\n";</lang>
say @pi[^(@pi.first: * >= 22, :k)].batch(10)».fmt('%2d').join: "\n";</syntaxhighlight>
{{out}}
{{out}}
<pre> 0 1 2 2 3 3 4 4 4 4
<pre> 0 1 2 2 3 3 4 4 4 4
Line 458: Line 798:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program finds and displays pi(n) for 0 < N ≤ prime(22) {the 22nd prime is 87},*/
<syntaxhighlight lang="rexx">/*REXX program finds and displays pi(n) for 0 < N ≤ prime(22) {the 22nd prime is 87},*/
/*────────────────────────── where the pi function returns the number of primes ≤ N.*/
/*────────────────────────── where the pi function returns the number of primes ≤ N.*/
parse arg hi cols . /*obtain optional argument from the CL.*/
parse arg hi cols . /*obtain optional argument from the CL.*/
Line 465: Line 805:
call genP /*build array of semaphores for primes.*/
call genP /*build array of semaphores for primes.*/
w= 10 /*width of a number in any column. */
w= 10 /*width of a number in any column. */
@pips= ' number of primes that are (for all N) ≤ prime(22) which is ' commas(@.hi)
title= ' number of primes that are (for all N) ≤ prime(22) which is ' commas(@.hi)
if cols>0 then say ' index │'center(@pips, 1 + cols*(w+1) )
if cols>0 then say ' index │'center(title, 1 + cols*(w+1) )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
idx= 1 /*initialize the index of output lines.*/
idx= 1 /*initialize the index of output lines.*/
$=; pips= 0 /*a list of piPrimes numbers (so far). */
$=; pips= 0 /*a list of piPrimes numbers (so far). */
do j=1 for @.hi-1 /*gen list of piPrime numbers<prime(hi)*/
do j=1 for @.hi-1 /*gen list of piPrime numbers<prime(hi)*/
if !.j then pips= pips + 1 /*Is J prime? Then bump pips number.*/
if !.j then pips= pips + 1 /*Is J prime? Then bump pips number.*/
if cols==0 then iterate /*Build the list (to be shown later)? */
if cols<0 then iterate /*Build the list (to be shown later)? */
c= commas(pips) /*maybe add commas to the number. */
c= commas(pips) /*maybe add commas to the number. */
$= $ right(c, max(w, length(c) ) ) /*add a Frobenius #──►list, allow big #*/
$= $ right(c, max(w, length(c) ) ) /*add a Frobenius #──►list, allow big #*/
if j//cols\==0 then iterate /*have we populated a line of output? */
if j//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
idx= idx + cols /*bump the index count for the output*/
Line 481: Line 821:


if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─')
say
say
say 'Found ' commas(j-1)", the" @pips
say 'Found ' commas(j-1)", the" title /*display the foot separator for output*/
exit 0 /*stick a fork in it, we're all done. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
Line 501: Line 842:
end /*k*/ /* [↑] only process numbers ≤ √ J */
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; s.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# */
#= #+1; @.#= j; s.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# */
end /*j*/; return</lang>
end /*j*/; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 514: Line 855:
61 │ 18 18 18 18 18 18 19 19 19 19
61 │ 18 18 18 18 18 18 19 19 19 19
71 │ 20 20 21 21 21 21 21 21
71 │ 20 20 21 21 21 21 21 21
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────


Found 78, the number of primes that are (for all N) ≤ prime(22) which is 79
Found 78, the number of primes that are (for all N) ≤ prime(22) which is 79
Line 519: Line 861:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
load "stdlib.ring"
load "stdlib.ring"


Line 552: Line 894:
see nl + "Found " + row + " Piprimes." + nl
see nl + "Found " + row + " Piprimes." + nl
see "done..." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 569: Line 911:
</pre>
</pre>


Pi primes ✔
=={{header|RPL}}==
{{works with|HP|49g}}
≪ 0
1 ROT '''FOR''' j j ISPRIME? + '''NEXT'''
≫ '<span style="color:blue">PI</span>' STO
≪ 0 → n
≪ { } 1 CF
'''DO'''
'n' INCR <span style="color:blue">PI</span>
'''IF''' DUP 22 ≤ '''THEN''' + '''ELSE''' DROP 1 SF '''END'''
'''UNTIL''' 1 FS? '''END'''
≫ '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
1: { 0. 1. 2. 2. 3. 3. 4. 4. 4. 4. 5. 5. 6. 6. 6. 6. 7. 7. 8. 8. 8. 8. 9. 9. 9. 9. 9. 9. 10. 10. 11. 11. 11. 11. 11. 11. 12. 12. 12. 12. 13. 13. 14. 14. 14. 14. 15. 15. 15. 15. 15. 15. 16. 16. 16. 16. 16. 16. 17. 17. 18. 18. 18. 18. 18. 18. 19. 19. 19. 19. 20. 20. 21. 21. 21. 21. 21. 21. }
</pre>

=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'prime'

pi = 0
pies = (1..).lazy.map {|n| n.prime? ? pi += 1 : pi}.take_while{ pi < 22 }
pies.each_slice(10){|s| puts "%3d"*s.size % s}</syntaxhighlight>
{{out}}
<pre> 0 1 2 2 3 3 4 4 4 4
5 5 6 6 6 6 7 7 8 8
8 8 9 9 9 9 9 9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21
</pre>
=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>1..(prime(22)-1) -> map { .prime_count }.say</lang>
<syntaxhighlight lang="ruby">1..(prime(22)-1) -> map { .prime_count }.say</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 578: Line 955:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-math}}
{{libheader|Wren-math}}
{{libheader|Wren-seq}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/math" for Int
<syntaxhighlight lang="wren">import "./math" for Int
import "/seq" for Lst
import "./fmt" for Fmt
import "/fmt" for Fmt


var primes = Int.primeSieve(79) // go up to the 22nd
var primes = Int.primeSieve(79) // go up to the 22nd
Line 599: Line 974:
}
}
System.print("pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:")
System.print("pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:")
for (chunk in Lst.chunks(pi, 10)) Fmt.print("$2d", chunk)
Fmt.tprint("$2d", pi, 10)
System.print("\nHighest n for this range = %(pi.count).")</lang>
System.print("\nHighest n for this range = %(pi.count).")</syntaxhighlight>


{{out}}
{{out}}
Line 618: Line 993:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>func IsPrime(N); \Return 'true' if N is a prime number
<syntaxhighlight lang="xpl0">func IsPrime(N); \Return 'true' if N is a prime number
int N, I;
int N, I;
[if N <= 1 then return false;
[if N <= 1 then return false;
Line 635: Line 1,010:
if IsPrime(P) then N:= N+1;
if IsPrime(P) then N:= N+1;
until N >= 22;
until N >= 22;
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}

Latest revision as of 12:03, 25 January 2024

Piprimes is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.


Task

pi(n), the number of primes <= n, where pi(n) < 22


Also see



11l

Translation of: Nim
F is_prime(n)
   I n == 2
      R 1B
   I n < 2 | n % 2 == 0
      R 0B
   L(i) (3 .. Int(sqrt(n))).step(2)
      I n % i == 0
         R 0B
   R 1B

V pi = 0
V n = 1
L
   print(‘#2’.format(pi), end' I n % 10 == 0 {"\n"} E ‘ ’)
   n++
   I is_prime(n)
      pi++
      I pi == 22
         L.break
print()
Output:
 0  1  2  2  3  3  4  4  4  4
 5  5  6  6  6  6  7  7  8  8
 8  8  9  9  9  9  9  9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21 

Action!

INCLUDE "H6:SIEVE.ACT"

PROC Main()
  DEFINE MAX="100"
  BYTE ARRAY primes(MAX+1)
  INT n=[0],p=[1]

  Put(125) PutE() ;clear the screen
  Sieve(primes,MAX+1)
  WHILE n<22
  DO
    PrintB(n) Put(32)
    p==+1
    IF primes(p) THEN
      n==+1
    FI
  OD
RETURN
Output:

Screenshot from Atari 8-bit computer

0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14
14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21

ALGOL 68

BEGIN # Show some values of pi(n) - the number of priems <= n  #
    # show pi(n) for n up to 21 #
    INT max prime = 100; # guess of how large the primes we need are # 
    INT max pi    = 21;
    PR read "primes.incl.a68" PR
    []BOOL prime = PRIMESIEVE max prime;
    INT pi        := 0;
    FOR i TO UPB prime
    WHILE IF prime[ i ] THEN pi +:= 1 FI;
          pi <= max pi
    DO
        print( ( " ", whole( pi, -2 ) ) );
        IF i MOD 10 = 0 THEN print( ( newline ) ) FI
    OD
END
Output:
  0  1  2  2  3  3  4  4  4  4
  5  5  6  6  6  6  7  7  8  8
  8  8  9  9  9  9  9  9 10 10
 11 11 11 11 11 11 12 12 12 12
 13 13 14 14 14 14 15 15 15 15
 15 15 16 16 16 16 16 16 17 17
 18 18 18 18 18 18 19 19 19 19
 20 20 21 21 21 21 21 21

Arturo

primes: select 2..1000 => prime?
piprimes: function [n] -> size select primes 'z [z =< n]

loop split.every: 10 select map 1..100 => piprimes => [& < 22] 'a -> 
    print map a => [pad to :string & 3]
Output:
  0   1   2   2   3   3   4   4   4   4 
  5   5   6   6   6   6   7   7   8   8 
  8   8   9   9   9   9   9   9  10  10 
 11  11  11  11  11  11  12  12  12  12 
 13  13  14  14  14  14  15  15  15  15 
 15  15  16  16  16  16  16  16  17  17 
 18  18  18  18  18  18  19  19  19  19 
 20  20  21  21  21  21  21  21

AWK

# syntax: GAWK -f PIPRIMES.AWK
# converted from FreeBASIC
BEGIN {
    while (1) {
      if (is_prime(++curr)) {
        running++
      }
      if (running == 22) {
        break
      }
      printf("%3d%1s",running,++count%10?"":"\n")
    }
    printf("\nPiPrimes 1-%d: %d\n",running-1,count)
    exit(0)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}
Output:
  0   1   2   2   3   3   4   4   4   4
  5   5   6   6   6   6   7   7   8   8
  8   8   9   9   9   9   9   9  10  10
 11  11  11  11  11  11  12  12  12  12
 13  13  14  14  14  14  15  15  15  15
 15  15  16  16  16  16  16  16  17  17
 18  18  18  18  18  18  19  19  19  19
 20  20  21  21  21  21  21  21
PiPrimes 1-21: 78

BASIC

BASIC256

Translation of: FreeBASIC
function isPrime(v)
	if v < 2 then return False
	if v mod 2 = 0 then return v = 2
	if v mod 3 = 0 then return v = 3
	d = 5
	while d * d <= v
		if v mod d = 0 then return False else d += 2
	end while
	return True
end function

running = 0 : curr = 0 : limite = 22
while True
	curr += 1
	if isPrime(curr) then running += 1
	if running = limite then exit while
	print running; "  ";
end while
end
Output:
Igual que la entrada de FreeBASIC.

FreeBASIC

#define UPTO 22
#include "isprime.bas"

dim as integer running = 0, curr=0
do 
    curr += 1
    if isprime(curr) then running += 1
    if running = UPTO then exit do
    print running;" ";
loop 
print : end
Output:

 0  1  2  2  3  3  4  4  4  4  5  5  6  6  6  6  7  7  8  8  8  8  9  9  9  9  9  9  10  10  11  11  11  11  11  11  12  12  12  12  13  13  14  14  14  14  15  15  15  15  15  15  16  16  16  16  16  16  17  17  18  18  18  18  18  18  19  19  19  19  20  20  21  21  21  21  21  21

Tiny BASIC

    LET N = 0
    LET P = 0
 10 IF N = 22 THEN END
    PRINT N
    LET P = P + 1
    GOSUB 100
 20 IF Z = 1 THEN LET N = N + 1
    GOTO 10
100 REM PRIMALITY BY TRIAL DIVISION
    LET Z = 1
    LET I = 2
110 IF (P/I)*I = P THEN LET Z = 0
    IF Z = 0 THEN RETURN
    LET I = I + 1
    IF I*I <= P THEN GOTO 110
    RETURN

Yabasic

Translation of: FreeBASIC
sub isPrime(v)
    if v < 2 then return False : fi
    if mod(v, 2) = 0 then return v = 2 : fi
    if mod(v, 3) = 0 then return v = 3 : fi
    d = 5
    while d * d <= v
        if mod(v, d) = 0 then return False else d = d + 2 : fi
    wend
    return True
end sub

running = 0 : curr = 0 : limite = 22
do 
    curr = curr + 1
    if isPrime(curr) then running = running + 1 : fi
    if running = limite break
    print running using "##", " ";
loop 
end
Output:
Igual que la entrada de FreeBASIC.


C

#include <stdio.h>
#include <stdlib.h>

int isprime( int n ) {
	int i;
        if (n<2) return 0;
	for(i=2; i*i<=n; i++) {
		if (n % i == 0) {return 0;}
	}
	return 1;
}

int main(void)  {
	int n = 0, p = 1;
	while (n<22) {
		printf( "%d   ", n );
		p++;
		if (isprime(p)) n+=1;
        }
	return 0;
}
Output:
0   1   2   2   3   3   4   4   4   4   5   5   6   6   6   6   7   7   8   8   8   8   9   9   9   9   9   9   10   10   11   11   11   11   11   11   12   12   12   12   13   13   14   14   14   14   15   15   15   15   15   15   16   16   16   16   16   16   17   17   18   18   18   18   18   18   19   19   19   19   20   20   21   21   21   21   21   21

Cowgol

include "cowgol.coh";

sub isPrime(n: uint8): (r: uint8) is
    var i: uint8 := 2;
    r := 0;
    if n>=2 then
        while i*i <= n loop
            if n%i == 0 then
                return;
            end if;
            i := i + 1;
        end loop;
        r := 1;
    end if;
end sub;

var count: uint8 := 0;
var n: uint8 := 1;
const MAX := 22;

while count < MAX loop
    print_i8(count);
    print_char('\t');
    n := n + 1;
    count := count + isPrime(n);
    if n % 10 == 1 then
        print_nl();
    end if;
end loop;
print_nl();
Output:
0       1       2       2       3       3       4       4       4       4
5       5       6       6       6       6       7       7       8       8
8       8       9       9       9       9       9       9       10      10
11      11      11      11      11      11      12      12      12      12
13      13      14      14      14      14      15      15      15      15
15      15      16      16      16      16      16      16      17      17
18      18      18      18      18      18      19      19      19      19
20      20      21      21      21      21      21      21

Dart

Translation of: C
import 'dart:math';
import 'dart:io';

void main() {
  int n = 0, p = 1;
  while (n < 22) {
    stdout.write("$n  ");
    ++p;
    if (isPrime(p))  ++n;
  }
}

bool isPrime(int n) {
  if (n <= 1) return false;
  if (n == 2) return true;
  for (int i = 2; i <= sqrt(n); ++i) {
    if (n % i == 0) return false;
  }
  return true;
}

Delphi

Works with: Delphi version 6.0


function IsPrime(N: int64): boolean;
{Fast, optimised prime test}
var I,Stop: int64;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
     begin
     I:=5;
     Stop:=Trunc(sqrt(N+0.0));
     Result:=False;
     while I<=Stop do
           begin
           if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
           Inc(I,6);
           end;
     Result:=True;
     end;
end;





procedure ShowPiprimes(Memo: TMemo);
var N, P, Cnt: integer;
var S: string;
begin
N:= 0;
P:= 1;
Cnt:= 0;
S:='';
repeat
	begin
	S:=S+Format('%3D',[N]);
	Inc(Cnt);
	if (Cnt mod 10)=0 then S:=S+CRLF;
	Inc(P);
        if IsPrime(P) then N:= N+1;
        end
until N >= 22;
Memo.Lines.Add(S);
end;
Output:
  0  1  2  2  3  3  4  4  4  4
  5  5  6  6  6  6  7  7  8  8
  8  8  9  9  9  9  9  9 10 10
 11 11 11 11 11 11 12 12 12 12
 13 13 14 14 14 14 15 15 15 15
 15 15 16 16 16 16 16 16 17 17
 18 18 18 18 18 18 19 19 19 19
 20 20 21 21 21 21 21 21
Elapsed Time: 1.328 ms.


F#

This task uses Extensible Prime Generator (F#)

// PiPrimes: Nigel Galloway. April 5th., 2021
let fN=let i=primes32() in Seq.unfold(fun(n,g,l)->Some(l,if n=g then (n+1,Seq.head i,l+1) else (n+1,g,l)))(1,Seq.head i,0)
fN|>Seq.takeWhile((>)22)|>Seq.chunkBySize 20|>Seq.iter(fun n->Array.iter(printf "%2d ") n; printfn "")
Output:
 0  0  1  2  2  3  3  4  4  4  4  5  5  6  6  6  6  7  7  8
 8  8  8  9  9  9  9  9  9 10 10 11 11 11 11 11 11 12 12 12
12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17
17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21

Factor

Works with: Factor version 0.99 2021-02-05
USING: formatting grouping io lists math.primes
math.primes.lists math.ranges math.statistics sequences ;

21 lprimes lnth [1,b) [ prime? ] cum-count
10 group [ [ "%2d " printf ] each nl ] each
Output:
 0  1  2  2  3  3  4  4  4  4 
 5  5  6  6  6  6  7  7  8  8 
 8  8  9  9  9  9  9  9 10 10 
11 11 11 11 11 11 12 12 12 12 
13 13 14 14 14 14 15 15 15 15 
15 15 16 16 16 16 16 16 17 17 
18 18 18 18 18 18 19 19 19 19 
20 20 21 21 21 21 21 21 

Fermat

n:=0; p:=0
while n<22 do !n;!' ';p:=p+1;if Isprime(p)=1 then n:=n+1; fi; od
Output:

0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21

FOCAL

01.10 S C=0
01.20 S N=1
01.30 T %3,C
01.40 S N=N+1
01.50 D 2;S C=C+A
01.60 I (C-22)1.3
01.70 T !
01.80 Q

02.10 S I=1
02.20 S I=I+1
02.30 I (I*I-N-1)2.4;S A=1;R
02.40 S A=N/I
02.50 I (FITR(A)-A)2.2;S A=0
Output:
=   0=   1=   2=   2=   3=   3=   4=   4=   4=   4=   5=   5=   6=   6=   6=   6
=   7=   7=   8=   8=   8=   8=   9=   9=   9=   9=   9=   9=  10=  10=  11=  11
=  11=  11=  11=  11=  12=  12=  12=  12=  13=  13=  14=  14=  14=  14=  15=  15
=  15=  15=  15=  15=  16=  16=  16=  16=  16=  16=  17=  17=  18=  18=  18=  18
=  18=  18=  19=  19=  19=  19=  20=  20=  21=  21=  21=  21=  21=  21


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


local fn Piprimes( limit as NSUInteger )
  NSUInteger n = 0, p = 1
  
  printf @"Piprimes from 1 through %lu:\n", limit
  while ( n < limit )
    printf @"%2lu  \b", n
    if p mod 10 == 0 then print
    p++
    if ( fn IsPrime(p) ) then n++
  wend
end fn

fn Piprimes( 22 )

HandleEvents
Output:

}

Piprimes from 1 through 22:

  0  1  2  2  3  3  4  4  4  4
  5  5  6  6  6  6  7  7  8  8
  8  8  9  9  9  9  9  9 10 10
 11 11 11 11 11 11 12 12 12 12
 13 13 14 14 14 14 15 15 15 15
 15 15 16 16 16 16 16 16 17 17
 18 18 18 18 18 18 19 19 19 19
 20 20 21 21 21 21 21 21

J

}.@(>:@i.&.p:) 21
Output:
0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21

Go

Translation of: Wren
Library: Go-rcu
package main

import (
    "fmt"
    "rcu"
)

func main() {
    primes := rcu.Primes(79) // go up to the 22nd
    ix := 0
    n := 1
    count := 0
    var pi []int
    for {
        if primes[ix] <= n {
            count++
            if count == 22 {
                break
            }
            ix++
        }
        n++
        pi = append(pi, count)
    }
    fmt.Println("pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:")
    for i, n := range pi {
        fmt.Printf("%2d ", n)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n\nHighest n for this range = %d.\n", len(pi))
}
Output:
pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:
 0  1  2  2  3  3  4  4  4  4 
 5  5  6  6  6  6  7  7  8  8 
 8  8  9  9  9  9  9  9 10 10 
11 11 11 11 11 11 12 12 12 12 
13 13 14 14 14 14 15 15 15 15 
15 15 16 16 16 16 16 16 17 17 
18 18 18 18 18 18 19 19 19 19 
20 20 21 21 21 21 21 21 

Highest n for this range = 78.

jq

Works with: jq

Works with gojq, the Go implementation of jq

This entry uses an approach based on streams of unbounded length; this has the advantage that no guessing or smarts is needed, either to provide a solution for the given bound (pi(n)<22) or any such bound.

For a suitable implementation of `is_prime` see e.g. Erdős-primes#jq.

Preliminaries

def count(s): reduce s as $x (null; .+1);

def emit_until(cond; stream):
  label $out | stream | if cond then break $out else . end;

def next_prime:
  if . == 2 then 3
  else first(range(.+2; infinite; 2) | select(is_prime))
  end;

The task

# Generate pi($n) for $n > 0
def pi_primes:
  foreach range(1; infinite) as $i ({n:0, np: 2};  # n counts, np is the next prime
     if $i < .np then .
     elif $i == .np then .n += 1 | .np |= next_prime
     else .
     end;
     .n);

emit_until(. >= 22; pi_primes)
Output:
0
1
2
2
3
3
4
4
4
4
...
19
19
19
19
20
20
21
21
21
21
21
21

Julia

using Primes

function listpiprimes(maxpi)
    pmask = primesmask(1, maxpi * maxpi)
    n = 0
    for (i, isp) in enumerate(pmask)
        isp == 1 && (n += 1) >= maxpi && break
        print(rpad(n, 3), i % 10 == 0 ? "\n" : "")
    end
end

listpiprimes(22)
Output:
0  1  2  2  3  3  4  4  4  4  
5  5  6  6  6  6  7  7  8  8
8  8  9  9  9  9  9  9  10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21

Mathematica/Wolfram Language

pi = PrimePi /@ Range[Prime[22] - 1];
Multicolumn[pi, {Automatic, 10}, Appearance -> "Horizontal"]
Output:
0	1	2	2	3	3	4	4	4	4
5	5	6	6	6	6	7	7	8	8
8	8	9	9	9	9	9	9	10	10
11	11	11	11	11	11	12	12	12	12
13	13	14	14	14	14	15	15	15	15
15	15	16	16	16	16	16	16	17	17
18	18	18	18	18	18	19	19	19	19
20	20	21	21	21	21	21	21		

Nim

import strutils

func isPrime(n: Natural): bool =
  if n < 2: return false
  if n mod 2 == 0: return n == 2
  if n mod 3 == 0: return n == 3
  var d = 5
  while d * d <= n:
    if n mod d == 0: return false
    inc d, 2
    if n mod d == 0: return false
    inc d, 4
  result = true

var pi = 0
var n = 1
while true:
  stdout.write ($pi).align(2), if n mod 10 == 0: '\n' else: ' '
  inc n
  if n.isPrime:
    inc pi
    if pi == 22: break
echo()


Output:
 0  1  2  2  3  3  4  4  4  4
 5  5  6  6  6  6  7  7  8  8
 8  8  9  9  9  9  9  9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21 

PARI/GP

n = 1;
while( primepi( n ) < 22,
    printf( "%3d", primepi(n) );
    if( n++ % 10 == 1,
        print()) )
Output:
 0  1  2  2  3  3  4  4  4  4
 5  5  6  6  6  6  7  7  8  8
 8  8  9  9  9  9  9  9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21

Perl

Library: ntheory
use strict;
use warnings;
use feature 'state';
use ntheory 'is_prime';

my @pi = map { state $pi = 0; $pi += is_prime $_ ? 1 : 0 } 1..1e4;
do { print shift(@pi) . ' ' } until $pi[0] >= 22;
Output:
0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21

Phix

with javascript_semantics
integer ix = 1, n = 1, count = 0
sequence pi = {}
while true do
    if get_prime(ix)<=n then
       count += 1
       if count>=22 then exit end if
       ix += 1
    end if
    n += 1
    pi = append(pi,sprintf("%2d",count))
end while
printf(1,"pi[1..%d]:\n%s\n",{length(pi),join_by(pi,1,10)})
Output:
pi[1..78]:
 0    1    2    2    3    3    4    4    4    4
 5    5    6    6    6    6    7    7    8    8
 8    8    9    9    9    9    9    9   10   10
11   11   11   11   11   11   12   12   12   12
13   13   14   14   14   14   15   15   15   15
15   15   16   16   16   16   16   16   17   17
18   18   18   18   18   18   19   19   19   19
20   20   21   21   21   21   21   21

Quackery

isprime is defined at Primality by trial division#Quackery.

  [ 0 swap
    1 - times
      [ i 1+ isprime + ] ]              is pi ( n --> n )

 2 [ dup pi dup 22 < while
     echo sp 1+ again ]
 2drop
Output:
0 1 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8 8 8 8 9 9 9 9 9 9 10 10 11 11 11 11 11 11 12 12 12 12 13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17 18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21

Raku

my @pi = (1..*).map: { state $pi = 0; $pi += .is-prime };

say @pi[^(@pi.first: * >= 22, :k)].batch(10)».fmt('%2d').join: "\n";
Output:
 0  1  2  2  3  3  4  4  4  4
 5  5  6  6  6  6  7  7  8  8
 8  8  9  9  9  9  9  9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21

REXX

/*REXX program finds and displays  pi(n)  for 0 < N ≤ prime(22)  {the 22nd prime is 87},*/
/*────────────────────────── where the  pi  function returns the number of primes  ≤  N.*/
parse arg hi cols .                              /*obtain optional argument from the CL.*/
if   hi=='' |   hi==","  then   hi= 22           /* "      "         "   "   "     "    */
if cols=='' | cols==","  then cols= 10           /* "      "         "   "   "     "    */
call genP                                        /*build array of semaphores for primes.*/
w= 10                                            /*width of a number in any column.     */
title= ' number of primes that are  (for all  N)  ≤  prime(22)   which is '   commas(@.hi)
if cols>0  then say ' index │'center(title, 1 + cols*(w+1)     )
if cols>0  then say '───────┼'center(""   , 1 + cols*(w+1), '─')
idx= 1                                           /*initialize the index of output lines.*/
$=;                     pips= 0                  /*a list of piPrimes numbers (so far). */
     do j=1  for @.hi-1                          /*gen list of piPrime numbers<prime(hi)*/
     if !.j  then pips= pips + 1                 /*Is J prime?  Then bump  pips  number.*/
     if cols<0       then iterate                /*Build the list  (to be shown later)? */
     c= commas(pips)                             /*maybe add commas to the number.      */
     $= $  right(c, max(w, length(c) ) )         /*add a Frobenius #──►list, allow big #*/
     if j//cols\==0  then iterate                /*have we populated a line of output?  */
     say center(idx, 7)'│'  substr($, 2);   $=   /*display what we have so far  (cols). */
     idx= idx + cols                             /*bump the  index  count for the output*/
     end   /*j*/

if $\==''  then say center(idx, 7)"│"  substr($, 2)  /*possible display residual output.*/
if cols>0  then say '───────┴'center(""  ,  1 + cols*(w+1), '─')
say
say 'Found '     commas(j-1)",  the"      title  /*display the foot separator for output*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end;  return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: !.= 0                                      /*placeholders for primes (semaphores).*/
      @.1=2;  @.2=3;  @.3=5;  @.4=7;  @.5=11     /*define some low primes.              */
      !.2=1;  !.3=1;  !.5=1;  !.7=1;  !.11=1     /*   "     "   "    "     flags.       */
                        #=5;     s.#= @.# **2    /*number of primes so far;     prime². */
                                                 /* [↓]  generate more  primes  ≤  high.*/
        do j=@.#+2  by 2  until #>hi             /*find odd primes from here on.        */
        parse var j '' -1 _; if     _==5  then iterate  /*J divisible by 5?  (right dig)*/
                             if j// 3==0  then iterate  /*"     "      " 3?             */
                             if j// 7==0  then iterate  /*"     "      " 7?             */
                                                 /* [↑]  the above  3  lines saves time.*/
               do k=5  while s.k<=j              /* [↓]  divide by the known odd primes.*/
               if j // @.k == 0  then iterate j  /*Is  J ÷ X?  Then not prime.     ___  */
               end   /*k*/                       /* [↑]  only process numbers  ≤  √ J   */
        #= #+1;    @.#= j;    s.#= j*j;   !.j= 1 /*bump # of Ps; assign next P;  P²; P# */
        end          /*j*/;               return
output   when using the default inputs:
 index │                      number of primes that are  (for all  N)  ≤  prime(22)   which is  79
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
   1   │          0          1          2          2          3          3          4          4          4          4
  11   │          5          5          6          6          6          6          7          7          8          8
  21   │          8          8          9          9          9          9          9          9         10         10
  31   │         11         11         11         11         11         11         12         12         12         12
  41   │         13         13         14         14         14         14         15         15         15         15
  51   │         15         15         16         16         16         16         16         16         17         17
  61   │         18         18         18         18         18         18         19         19         19         19
  71   │         20         20         21         21         21         21         21         21
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────

Found  78,  the  number of primes that are  (for all  N)  ≤  prime(22)   which is  79

Ring

load "stdlib.ring"

decimals(0) 
see "working..." + nl
see "Piprimes are:" + nl

row = 0
limit1 = 400
Prim = []

for n = 1 to limit1
    if isprime(n)
       add(Prim,n)
    ok
next

for n = 1 to len(Prim)
    for m = 1 to len(Prim)
        if Prim[m] > n
           ind = m - 1
           exit
        ok
    next
    row = row + 1
    see "" + ind + " "
    if row%10 = 0
       see nl
    ok
next

see nl + "Found " + row + " Piprimes." + nl
see "done..." + nl
Output:
working...
Piprimes are:
0 1 2 2 3 3 4 4 4 4 
5 5 6 6 6 6 7 7 8 8 
8 8 9 9 9 9 9 9 10 10 
11 11 11 11 11 11 12 12 12 12 
13 13 14 14 14 14 15 15 15 15 
15 15 16 16 16 16 16 16 17 17 
18 18 18 18 18 18 19 19 19 19 
20 20 21 21 21 21 21 21 
Found 78 Piprimes.
done...

Pi primes ✔

RPL

Works with: HP version 49g
≪ 0
   1 ROT FOR j j ISPRIME? + NEXT
≫ 'PI' STO

≪ 0 → n
  ≪ { } 1 CF
     DO 
       'n' INCR PI
        IF DUP 22 ≤ THEN + ELSE DROP 1 SF END
     UNTIL 1 FS? END
≫ 'TASK' STO
Output:
1: { 0. 1. 2. 2. 3. 3. 4. 4. 4. 4. 5. 5. 6. 6. 6. 6. 7. 7. 8. 8. 8. 8. 9. 9. 9. 9. 9. 9. 10. 10. 11. 11. 11. 11. 11. 11. 12. 12. 12. 12. 13. 13. 14. 14. 14. 14. 15. 15. 15. 15. 15. 15. 16. 16. 16. 16. 16. 16. 17. 17. 18. 18. 18. 18. 18. 18. 19. 19. 19. 19. 20. 20. 21. 21. 21. 21. 21. 21. }

Ruby

require 'prime'

pi = 0
pies = (1..).lazy.map {|n| n.prime? ? pi += 1 : pi}.take_while{ pi < 22 }
pies.each_slice(10){|s| puts "%3d"*s.size % s}
Output:
  0  1  2  2  3  3  4  4  4  4
  5  5  6  6  6  6  7  7  8  8
  8  8  9  9  9  9  9  9 10 10
 11 11 11 11 11 11 12 12 12 12
 13 13 14 14 14 14 15 15 15 15
 15 15 16 16 16 16 16 16 17 17
 18 18 18 18 18 18 19 19 19 19
 20 20 21 21 21 21 21 21

Sidef

1..(prime(22)-1) -> map { .prime_count }.say
Output:
[0, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 21, 21, 21, 21, 21, 21]

Wren

Library: Wren-math
Library: Wren-fmt
import "./math" for Int
import "./fmt" for Fmt

var primes = Int.primeSieve(79) // go up to the 22nd
var ix = 0
var n = 1
var count = 0
var pi = []
while (true) {
    if (primes[ix] <= n) {
       count = count + 1
       if (count == 22) break
       ix = ix + 1
    }
    n = n + 1
    pi.add(count)
}
System.print("pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:")
Fmt.tprint("$2d", pi, 10)
System.print("\nHighest n for this range = %(pi.count).")
Output:
pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:
 0  1  2  2  3  3  4  4  4  4
 5  5  6  6  6  6  7  7  8  8
 8  8  9  9  9  9  9  9 10 10
11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15
15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19
20 20 21 21 21 21 21 21

Highest n for this range = 78.

XPL0

func IsPrime(N);        \Return 'true' if N is a prime number
int  N, I;
[if N <= 1 then return false;
for I:= 2 to sqrt(N) do
    if rem(N/I) = 0 then return false;
return true;
];

int Count, N, P;
[Count:= 0;  N:= 0;  P:= 1;
repeat  if N<10 then ChOut(0, ^ );
        IntOut(0, N);
        Count:= Count+1;
        if rem(Count/20) then ChOut(0, ^ ) else CrLf(0);
        P:= P+1;
        if IsPrime(P) then N:= N+1;
until   N >= 22;
]
Output:
 0  1  2  2  3  3  4  4  4  4  5  5  6  6  6  6  7  7  8  8
 8  8  9  9  9  9  9  9 10 10 11 11 11 11 11 11 12 12 12 12
13 13 14 14 14 14 15 15 15 15 15 15 16 16 16 16 16 16 17 17
18 18 18 18 18 18 19 19 19 19 20 20 21 21 21 21 21 21