diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-03-07 16:19:14 +0100 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-03-12 17:45:44 +0100 |
| commit | 1969434787f163f6da03c9c3cb6ea2c31cf97f9e (patch) | |
| tree | 2960c4fc9df22434de519c7329326568e277a71b /challenge-155 | |
| parent | c31583854c7b6df90b39c619efc47f91188c6a6f (diff) | |
| download | perlweeklychallenge-club-1969434787f163f6da03c9c3cb6ea2c31cf97f9e.tar.gz perlweeklychallenge-club-1969434787f163f6da03c9c3cb6ea2c31cf97f9e.tar.bz2 perlweeklychallenge-club-1969434787f163f6da03c9c3cb6ea2c31cf97f9e.zip | |
Solution to task 1
Diffstat (limited to 'challenge-155')
| -rwxr-xr-x | challenge-155/jo-37/perl/ch-1.pl | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/challenge-155/jo-37/perl/ch-1.pl b/challenge-155/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..ad2c142392 --- /dev/null +++ b/challenge-155/jo-37/perl/ch-1.pl @@ -0,0 +1,82 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; +use bigint; +use Math::Prime::Util qw(next_prime is_prime); +use Coro::Generator; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die <<EOS unless @ARGV; +usage: $0 [-examples] [-tests] [N] + +-examples + run the examples from the challenge + +-tests + run some tests + +N + Print the first N distinct fortunate numbers in ascending order. + +EOS + + +### Input and Output + +main: { + my $fn = gen_fortunate_numbers(); + my %fn; + # Collect the first N distinct fortunate numbers. + until (keys %fn == $ARGV[0]) { + $fn{$fn->()} = undef; + } + # Present in ascending order. + say for sort {$a <=> $b} keys %fn; +} + + +### Implementation + +# Build a generator for fortunate numbers. The resulting sequence is +# neither sorted nor does it consist of distinct values only. +sub gen_fortunate_numbers { + my $pn = 1; + my $p = 1; + + generator { + while () { + $pn *= ($p = next_prime($p)); + for (my $m = 2;; $m++) { + yield($m), last if is_prime($pn + $m); + } + } + } +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + my $fn = gen_fortunate_numbers(); + is [map $fn->(), 1 .. 9], [3, 5, 7, 13, 23, 17, 19, 23, 37], + 'the raw sequence: neither sorted nor distinct' + } + + SKIP: { + skip "tests" unless $tests; + + my $fn = gen_fortunate_numbers(); + $fn->() for 1 .. 57; + is $fn->(), 331, '#58 according to OEIS'; + } + + done_testing; + exit; +} |
