diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2021-06-07 20:51:21 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2021-06-11 14:35:17 +0200 |
| commit | 4eea29866b52e56ac78384fde69e85ad2b3d615b (patch) | |
| tree | e91deb35857be9fb08f95ff19685158bd448ec27 | |
| parent | 82c779e1fc289d1f875ebdec292f9d741811e627 (diff) | |
| download | perlweeklychallenge-club-4eea29866b52e56ac78384fde69e85ad2b3d615b.tar.gz perlweeklychallenge-club-4eea29866b52e56ac78384fde69e85ad2b3d615b.tar.bz2 perlweeklychallenge-club-4eea29866b52e56ac78384fde69e85ad2b3d615b.zip | |
Solution to task 2
| -rwxr-xr-x | challenge-116/jo-37/perl/ch-2.pl | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/challenge-116/jo-37/perl/ch-2.pl b/challenge-116/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..8e145a9dce --- /dev/null +++ b/challenge-116/jo-37/perl/ch-2.pl @@ -0,0 +1,66 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0; +use Math::Prime::Util qw(vecsum is_square); + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die <<EOS unless @ARGV; +usage: $0 [-examples] [-tests] [num] + +-examples + run the examples from the challenge + +-tests + run some tests + +num + check if the sum of the squared decimal digits of num is a perfect square + +EOS + + +### Input and Output + +say 0 + sum_of_squares_is_square(shift); + + +### Implementation + +sub sum_of_squares_is_square { + local $_ = shift; + # Input is restricted to N >= 10: + die "not valid\n" unless /^[1-9][0-9]+\z/; + + # The digits are subject to integer operations only, therefore there + # are no rounding issues. Takes a string, not an (internal) + # integer. + is_square vecsum map $_ * $_, split //; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + ok sum_of_squares_is_square(34), 'example 1'; + ok sum_of_squares_is_square(50), 'example 2'; + ok !sum_of_squares_is_square(52), 'example 3'; + } + + SKIP: { + skip "tests" unless $tests; + ok sum_of_squares_is_square(10), 'smallest number for given limit'; + ok sum_of_squares_is_square(236), 'three nonzero digits'; + ok sum_of_squares_is_square('1' x 196), '1**2 * 196 == 14**2'; + ok sum_of_squares_is_square('9' x 81), '9**2 * 81 == 81**2'; + } + + done_testing; + exit; +} |
