aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordcw <d.white@imperial.ac.uk>2022-04-10 22:26:13 +0100
committerdcw <d.white@imperial.ac.uk>2022-04-10 22:26:13 +0100
commitfb45a89ac758ddf2d942734971d06973660555ef (patch)
treee59d28153d0408730e22d5622222a7470af704c8
parenta499786d50c03329a0b1e5fdbce900a57b2af00c (diff)
downloadperlweeklychallenge-club-fb45a89ac758ddf2d942734971d06973660555ef.tar.gz
perlweeklychallenge-club-fb45a89ac758ddf2d942734971d06973660555ef.tar.bz2
perlweeklychallenge-club-fb45a89ac758ddf2d942734971d06973660555ef.zip
(as a bonus, added "--tabulate" mode to, well, tabulate moebius(x) for x=1..n
-rwxr-xr-xchallenge-159/duncan-c-white/perl/ch-2.pl30
1 files changed, 26 insertions, 4 deletions
diff --git a/challenge-159/duncan-c-white/perl/ch-2.pl b/challenge-159/duncan-c-white/perl/ch-2.pl
index 5df848adf8..ae80d2a6df 100755
--- a/challenge-159/duncan-c-white/perl/ch-2.pl
+++ b/challenge-159/duncan-c-white/perl/ch-2.pl
@@ -43,8 +43,10 @@ use MakePrimes;
use PrimeFactors;
my $debug=0;
-die "Usage: moebius [--debug] [N] (default 5)\n"
- unless GetOptions( "debug"=>\$debug ) && @ARGV<2;
+my $tabulate=0;
+die "Usage: moebius [--debug] [--tabulate] [N] (default 5)\n"
+ unless GetOptions( "debug"=>\$debug, "tabulate"=>\$tabulate )
+ && @ARGV<2;
my $n = shift // 5;
@@ -57,7 +59,9 @@ fun moeb( $n )
{
my @primes = primes_upto( $n );
- my @factors = prime_factors( $n, @primes );
+ my @factors;
+ @factors = prime_factors( $n, @primes ) if $n>1;
+ @factors = () if $n==1;
my %factorbag;
$factorbag{$_}++ for @factors;
@@ -86,4 +90,22 @@ fun moeb( $n )
return -1;
}
-say moeb( $n );
+if( $tabulate )
+{
+ my @lines;
+ my $line = '';
+ foreach my $i (1..$n)
+ {
+ $line .= sprintf( "%2d: %2d", $i, moeb($i) );
+ $line .= ', ';
+ if( $i % 10 == 0 )
+ {
+ push @lines, $line;
+ $line = '';
+ }
+ }
+ say for @lines;
+} else
+{
+ say moeb( $n );
+}