/
ch-1.p6
executable file
·46 lines (41 loc) · 1018 Bytes
/
ch-1.p6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#! /usr/bin/raku
use Test;
plan 3;
is(countprimes(10), 4, 'example 1');
is(countprimes(1), 0, 'example 2');
is(countprimes(20), 8, 'example 3');
sub genprimes($mx) {
my @primes;
{
my $primesh=(2..(3,$mx).min).SetHash;
loop (my $i=6;$i <= $mx+1; $i += 6) {
for ($i-1,$i+1) -> $j {
if ($j <= $mx) {
$primesh{$j}=True;
}
}
}
my $p=2;
my @q=[2,3,5,7];
my $mr=floor(sqrt($mx));
while ($p <= $mr) {
if ($primesh{$p}:exists) {
my $i=$p*$p;
while ($i <= $mx) {
$primesh{$i}:delete;
$i += $p;
}
}
if (@q.elems < 2) {
@q.push(@q[*-1]+4);
@q.push(@q[*-1]+2);
}
$p=@q.shift;
}
@primes=$primesh.keys.sort;
}
return @primes;
}
sub countprimes($l) {
return genprimes($l).elems;
}