diff options
| -rwxr-xr-x | challenge-146/wlmb/perl/ch-1.pl | 24 |
1 files changed, 14 insertions, 10 deletions
diff --git a/challenge-146/wlmb/perl/ch-1.pl b/challenge-146/wlmb/perl/ch-1.pl index 483b024a67..b65eddcb78 100755 --- a/challenge-146/wlmb/perl/ch-1.pl +++ b/challenge-146/wlmb/perl/ch-1.pl @@ -7,18 +7,22 @@ use v5.12; use warnings; use PDL; use PDL::NiceSlice; +use Try::Tiny; for my $N(@ARGV?@ARGV:10001){ - die "Argument should be positive" unless $N>=1; - # Estimate size $M of required sieve by solving $M/log($M) approx $N - # unless $N is too small - my $M=$N<4?6:find_zero(sub {my $x=shift; $N-$x/log($x)}, + try{ + die "Argument should be positive: $N" unless $N>=1; + # Estimate size $M of required sieve by solving $M/log($M) approx $N + # unless $N is too small + my $M=$N<4?6:find_zero(sub {my $x=shift; $N-$x/log($x)}, sub {my $l=log($_[0]); 1/$l**2-1/$l}, $N); - my $sieve=ones($M); # fill sieve with ones - $sieve(0:1).=0; # 0 and 1 are not primes - $sieve($_*$_:-1:$_).=0 foreach(2..sqrt($M-1)); # multiples of 'it' are not prime - my $primes=$sieve->xvals->where($sieve); # first primes - die "Short sieve" unless $N<=$primes->nelem; # shouldn't happen - say "$N-th prime is ", $primes(($N-1)); + my $sieve=ones($M); # fill sieve with ones + $sieve(0:1).=0; # 0 and 1 are not primes + $sieve($_*$_:-1:$_).=0 foreach(2..sqrt($M-1)); # multiples of 'it' are not prime + my $primes=$sieve->xvals->where($sieve); # first primes + die "Short sieve" unless $N<=$primes->nelem; # shouldn't happen + say "$N-th prime is ", $primes(($N-1)); + } + catch { say $_;} } no PDL::NiceSlice; # NiceSlice destroys indirect function calls! |
