diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-03-28 16:04:17 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-04-01 15:55:16 +0200 |
| commit | c4d805cf0d1c3463cfa8ae44fa0f686960705bd3 (patch) | |
| tree | 351c4d8673b611cf1304b651bae1173ea7a8d175 /challenge-158 | |
| parent | 94c76f89337d76da7cb27601d2b02a5553462bf9 (diff) | |
| download | perlweeklychallenge-club-c4d805cf0d1c3463cfa8ae44fa0f686960705bd3.tar.gz perlweeklychallenge-club-c4d805cf0d1c3463cfa8ae44fa0f686960705bd3.tar.bz2 perlweeklychallenge-club-c4d805cf0d1c3463cfa8ae44fa0f686960705bd3.zip | |
Solution to task 1
Diffstat (limited to 'challenge-158')
| -rwxr-xr-x | challenge-158/jo-37/perl/ch-1.pl | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/challenge-158/jo-37/perl/ch-1.pl b/challenge-158/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..e1e5db054f --- /dev/null +++ b/challenge-158/jo-37/perl/ch-1.pl @@ -0,0 +1,80 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; +use Math::Prime::Util qw(prime_iterator is_prime vecsum todigits); +use Coro::Generator; +use Syntax::Keyword::Gather; +use experimental 'signatures'; + +our ($tests, $examples, $base); +$base ||= 10; + +run_tests() if $tests || $examples; # does not return + +die <<EOS unless @ARGV; +usage: $0 [-examples] [-tests] [-base=B] [LIM] + +-examples + run the examples from the challenge + +-tests + run some tests + +-base=B + Use number representation in given base. + +LIM + Print additive primes below given limit. + +EOS + + +### Input and Output + +say for additive_primes_below(shift, $base); + + +### Implementation + +sub additive_primes_below ($limit, $base = 10) { + my $p_i = prime_iterator(); + + # Build a generator for additive primes in the given base. + my $ap_i = generator { + my $p; + while () { + yield $p if is_prime vecsum todigits $p = $p_i->(), $base; + } + }; + + # Collect all additive primes below the given limit. + gather { + my $ap; + take $ap while ($ap = $ap_i->()) < $limit; + }; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is scalar additive_primes_below(100), + [2, 3, 5, 7, 11, 23, 29, 41, 43, 47, 61, 67, 83, 89], + 'task 1'; + } + + SKIP: { + skip "tests" unless $tests; + + is scalar additive_primes_below(32, 2), + [3, 5, 7, 11, 13, 17, 19, 31], + 'pernicious primes'; + } + + done_testing; + exit; +} |
