aboutsummaryrefslogtreecommitdiff
path: root/challenge-109/jo-37
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2021-04-19 17:44:14 +0200
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2021-04-21 21:42:37 +0200
commitfccecc2765b5344e925e4379d3c822fbb674aa97 (patch)
treed1d1a9048a08859fb26f78737aaa0dd49eec7de9 /challenge-109/jo-37
parent39c3ac8c65f6fa3d0a86e5af47727eec086e162a (diff)
downloadperlweeklychallenge-club-fccecc2765b5344e925e4379d3c822fbb674aa97.tar.gz
perlweeklychallenge-club-fccecc2765b5344e925e4379d3c822fbb674aa97.tar.bz2
perlweeklychallenge-club-fccecc2765b5344e925e4379d3c822fbb674aa97.zip
Solution to task 1
Diffstat (limited to 'challenge-109/jo-37')
-rwxr-xr-xchallenge-109/jo-37/perl/ch-1.pl49
1 files changed, 49 insertions, 0 deletions
diff --git a/challenge-109/jo-37/perl/ch-1.pl b/challenge-109/jo-37/perl/ch-1.pl
new file mode 100755
index 0000000000..fd3ca1d792
--- /dev/null
+++ b/challenge-109/jo-37/perl/ch-1.pl
@@ -0,0 +1,49 @@
+#!/usr/bin/perl -s
+
+use v5.16;
+use Test2::V0;
+use Math::Prime::Util 'divisor_sum';
+use experimental 'signatures';
+
+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 the first n Chowla numbers
+
+EOS
+
+
+### Input and Output
+
+say join ', ', map chowla($_), 1 .. $ARGV[0];
+
+
+### Implementation
+
+# Return the n-th Chowla number as the sum of n's nontrivial divisors.
+# The trivial divisors are 1 and n, which need to be subtracted from the
+# sum of all divisors. For n = 1 these two numbers coincide and thus
+# only one subtrahend shall be applied.
+sub chowla ($n) {
+ divisor_sum($n) - $n - ($n > 1);
+}
+
+
+### Examples and tests
+
+sub run_tests {
+ my $n;
+ is chowla(++$n), $_, "chowla($n) = $_" for
+ (0, 0, 0, 2, 0, 5, 0, 6, 3, 7, 0, 15, 0, 9, 8, 14, 0, 20, 0, 21);
+
+ done_testing;
+ exit;
+}