aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael Lee Firkins <michael@firkins>2022-04-04 23:59:46 +0700
committerMichael Lee Firkins <michael@firkins>2022-04-05 12:29:53 +0700
commite408fdd922b96e10a1e1ee05be6f036ef5404d3e (patch)
treea980a390aa246c9b57b13d12a7c374beeda9a307
parent21b2771f7439710ee9a4631c40679a916ca9f723 (diff)
downloadperlweeklychallenge-club-e408fdd922b96e10a1e1ee05be6f036ef5404d3e.tar.gz
perlweeklychallenge-club-e408fdd922b96e10a1e1ee05be6f036ef5404d3e.tar.bz2
perlweeklychallenge-club-e408fdd922b96e10a1e1ee05be6f036ef5404d3e.zip
pwc159 solution in perl
-rw-r--r--challenge-159/pokgopun/perl/ch-1.pl33
-rw-r--r--challenge-159/pokgopun/perl/ch-2.pl20
2 files changed, 53 insertions, 0 deletions
diff --git a/challenge-159/pokgopun/perl/ch-1.pl b/challenge-159/pokgopun/perl/ch-1.pl
new file mode 100644
index 0000000000..d5fd2115d3
--- /dev/null
+++ b/challenge-159/pokgopun/perl/ch-1.pl
@@ -0,0 +1,33 @@
+use strict;
+use warnings;
+#use Algorithm::Combinatorics qw/combinations/;
+#use Math::Prime::Util qw/is_prime/;
+
+my @n = join("",@ARGV) =~ /^\d+$/ ? @ARGV : (5,7,4);
+
+foreach my $n (@n) {
+ print "Input: \$n = $n\n";
+
+### far too complicated, comes up with this before trying to read about Farey sequence
+# my @fs;
+# if ($n > 1) {
+# @fs = sort{$a->[0]/$a->[1] <=> $b->[0]/$b->[1]} grep{ $_->[0] == 1 || ( (is_prime($_->[0]) || is_prime($_->[1]) ) && $_->[1] % $_->[0] != 0 ) } combinations([1..$n], 2);
+# }
+# @fs = ([0,1], @fs, [1,1]);
+# printf "Output: %s\n\n", join(", ", map{join "/", @$_} @fs );
+
+### here is a simple algorithm found on https://en.wikipedia.org/wiki/Farey_sequence
+ my ($a,$b,$c,$d) = (0,1,1,$n);
+ printf "Output: %d/%d, %d/%d", $a, $b, $c, $d;
+ if ($n > 1){
+ {
+ my $k = int( ($n + $b) / $d );
+ ($a,$b,$c,$d) = ($c,$d,$k*$c-$a,$k*$d-$b);
+ printf", %d/%d", $c, $d;
+ last if $c==1 && $d==1;
+ redo
+ }
+ }
+ print "\n\n";
+
+}
diff --git a/challenge-159/pokgopun/perl/ch-2.pl b/challenge-159/pokgopun/perl/ch-2.pl
new file mode 100644
index 0000000000..b8c4b7fa50
--- /dev/null
+++ b/challenge-159/pokgopun/perl/ch-2.pl
@@ -0,0 +1,20 @@
+use strict;
+use warnings;
+use Math::Factoring qw/factor/;
+
+my @n = join("",@ARGV) =~ /^\d+$/ ? @ARGV : (5,10,20);
+foreach my $n (@n) {
+
+ print "Input: \$n = $n\n";
+
+ my %factor;
+ $factor{$_}++ foreach factor($n);
+
+ my @values = values %factor;
+ my $m = $n == 1 ? 1 :
+ scalar(grep{$_ > 1} @values) ? 0 :
+ @values % 2 ? -1 : 1;
+
+ print "Output: $m\n\n";
+}
+