aboutsummaryrefslogtreecommitdiff
path: root/challenge-156
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-03-17 23:08:22 +0100
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-03-18 19:33:41 +0100
commit4cbeb67e72a2cffafd396c3fb4f6b44d661c43f7 (patch)
tree69245ebe4ae2e8b3227aa793d141b2455b1bc0f8 /challenge-156
parentec40a817b49b92d42a652fc8edc3772697a29314 (diff)
downloadperlweeklychallenge-club-4cbeb67e72a2cffafd396c3fb4f6b44d661c43f7.tar.gz
perlweeklychallenge-club-4cbeb67e72a2cffafd396c3fb4f6b44d661c43f7.tar.bz2
perlweeklychallenge-club-4cbeb67e72a2cffafd396c3fb4f6b44d661c43f7.zip
Solution to task 1
Diffstat (limited to 'challenge-156')
-rwxr-xr-xchallenge-156/jo-37/perl/ch-1.pl71
1 files changed, 71 insertions, 0 deletions
diff --git a/challenge-156/jo-37/perl/ch-1.pl b/challenge-156/jo-37/perl/ch-1.pl
new file mode 100755
index 0000000000..6b3cfa6dd1
--- /dev/null
+++ b/challenge-156/jo-37/perl/ch-1.pl
@@ -0,0 +1,71 @@
+#!/usr/bin/perl -s
+
+use v5.16;
+use Test2::V0;
+use Math::Prime::Util qw(is_prime todigits vecsum);
+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 pernicious numbers
+
+EOS
+
+
+### Input and Output
+
+main: {
+ my $pn = gen_pernicious_numbers();
+ say $pn->() for 1 .. shift;
+}
+
+
+### Implementation
+
+# Build a generator for pernicious numbers.
+# This implementation is not optimal as we try all numbers and check
+# their binary representation. It might be more efficient to construct
+# the numbers from a prime number of bits.
+sub gen_pernicious_numbers {
+ generator {
+ for (my $n = 2;; $n++) {
+ yield $n if is_prime vecsum todigits $n, 2;
+ }
+ }
+}
+
+
+### Examples and tests
+
+sub run_tests {
+ SKIP: {
+ skip "examples" unless $examples;
+
+ my $pn = gen_pernicious_numbers();
+ is [map $pn->(), 1 .. 10], [3, 5, 6, 7, 9, 10, 11, 12, 13, 14],
+ 'task 1';
+ }
+
+ SKIP: {
+ skip "tests" unless $tests;
+
+ my $pn = gen_pernicious_numbers();
+ $pn->() for 1 .. 64;
+ is $pn->(), 100, '#65 from OEIS A052294';
+ }
+
+ done_testing;
+ exit;
+}