diff options
| author | Luis Mochan <mochan@fis.unam.mx> | 2022-01-03 19:41:29 -0600 |
|---|---|---|
| committer | Luis Mochan <mochan@fis.unam.mx> | 2022-01-03 19:41:29 -0600 |
| commit | a170c68911cae820e4ba05ab7a73c7a56a88188c (patch) | |
| tree | a261fce2c061f484b41bfe28f1b42cc1540175de | |
| parent | 673335faf79add44d5dc1128147d8112b5c5051a (diff) | |
| download | perlweeklychallenge-club-a170c68911cae820e4ba05ab7a73c7a56a88188c.tar.gz perlweeklychallenge-club-a170c68911cae820e4ba05ab7a73c7a56a88188c.tar.bz2 perlweeklychallenge-club-a170c68911cae820e4ba05ab7a73c7a56a88188c.zip | |
Add try/catch to task 1
| -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! |
