diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-01-31 10:14:36 +0100 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2022-02-05 22:39:39 +0100 |
| commit | 461d416ae4428e1011a1647c24feabe3a0452ec5 (patch) | |
| tree | 49951ee50b4108fa406e5982370cd1d48c94e0fa /challenge-150 | |
| parent | 657fcb86f66182031a41ba6a1f572e7c075eb1f3 (diff) | |
| download | perlweeklychallenge-club-461d416ae4428e1011a1647c24feabe3a0452ec5.tar.gz perlweeklychallenge-club-461d416ae4428e1011a1647c24feabe3a0452ec5.tar.bz2 perlweeklychallenge-club-461d416ae4428e1011a1647c24feabe3a0452ec5.zip | |
Solution to task 2
Diffstat (limited to 'challenge-150')
| -rwxr-xr-x | challenge-150/jo-37/perl/ch-2.pl | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/challenge-150/jo-37/perl/ch-2.pl b/challenge-150/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..a1ea3fe1bc --- /dev/null +++ b/challenge-150/jo-37/perl/ch-2.pl @@ -0,0 +1,57 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; +use Math::Prime::Util qw(factor_exp vecmax); +use Coro::Generator; + +our $examples; + +run_tests() if $examples; # does not return + +die <<EOS unless @ARGV == 1; +usage: $0 [-examples] [N] + +-examples + run the examples from the challenge + +N + Print first N square-free integers. + +EOS + + +### Input and Output + +main: { + my $sq_free = gen_square_free(); + say $sq_free->() for 1 .. $ARGV[0]; +} + + +### Implementation + +# Build a generator for square-free integers. +sub gen_square_free { + generator { + # Treat 1 separately as factor(1) returns an empty list. + yield 1; + for (my $n = 2;; $n++) { + # Check if the maximum exponent in N's factorization is one. + yield $n if 1 == vecmax map $_->[1], factor_exp $n; + } + } +} + + +### Examples and tests + +sub run_tests { + my $sq_free = gen_square_free(); + is [map $sq_free->(), 1 .. 19], + [1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30], + 'example 1'; + + done_testing; + exit; +} |
