diff options
| author | E7-87-83 <fungcheokyin@gmail.com> | 2022-04-10 12:45:26 +0800 |
|---|---|---|
| committer | E7-87-83 <fungcheokyin@gmail.com> | 2022-04-10 12:45:26 +0800 |
| commit | da06bf445680225ba91695236c1d86221e6192f5 (patch) | |
| tree | 6d8f444c92f3622538fb9abcf156d9a0f38cb374 | |
| parent | 9414d68b40f35f87256f83e01a21b3a619a6de42 (diff) | |
| download | perlweeklychallenge-club-da06bf445680225ba91695236c1d86221e6192f5.tar.gz perlweeklychallenge-club-da06bf445680225ba91695236c1d86221e6192f5.tar.bz2 perlweeklychallenge-club-da06bf445680225ba91695236c1d86221e6192f5.zip | |
Perl scripts
| -rw-r--r-- | challenge-159/perl/ch-1.pl | 45 | ||||
| -rw-r--r-- | challenge-159/perl/ch-2.pl | 4 |
2 files changed, 49 insertions, 0 deletions
diff --git a/challenge-159/perl/ch-1.pl b/challenge-159/perl/ch-1.pl new file mode 100644 index 0000000000..d6500f2c5f --- /dev/null +++ b/challenge-159/perl/ch-1.pl @@ -0,0 +1,45 @@ +#!/usr/bin/perl +# The Weekly Challenge 159 +# Task 1 Farey Sequence + +# https://en.wikipedia.org/wiki/Farey_sequence#Next_term + +use v5.22.0; +use warnings; +use POSIX; + +my $N = $ARGV[0] if defined($ARGV[0]); + +say farey($N) if defined($ARGV[0]); + + + +sub farey { + my $n = $_[0]; + die "The parameter should be a positive integer." if $n==0; + my ($g, $h) = ([0,1], [1, $n]); + my @terms; + do { + push @terms, "".join("/", $g->@*); + my ($a, $b) = $g->@*; + my ($c, $d) = $h->@*; + my ($p, $q) = ( + $c*floor (($n+$b)/$d) - $a, + $d*floor(($n+$b)/$d) - $b + ); + ($g, $h) = ($h, [$p, $q]); + } while (!($h->[0] == 1 && $h->[1] == 1)); + push @terms, join("/", $g->@*), join("/", $h->@*); + return join(", ",@terms) . "."; +} + + + +use Test::More tests => 3; +ok( + "0/1, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 1/1." + eq farey(5), "Example 1"); +ok( + "0/1, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 2/5, 3/7, 1/2, 4/7, 3/5," + . " 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 1/1." eq farey(7), "Example 2"); +ok("0/1, 1/4, 1/3, 1/2, 2/3, 3/4, 1/1." eq farey(4), "Example 3"); diff --git a/challenge-159/perl/ch-2.pl b/challenge-159/perl/ch-2.pl index 8efb6f5c41..0d58c1eeb4 100644 --- a/challenge-159/perl/ch-2.pl +++ b/challenge-159/perl/ch-2.pl @@ -25,6 +25,8 @@ sub irn { ); } + + sub mo { my $n = $_[0]; return 1 if $n == 1; @@ -38,6 +40,8 @@ sub mo { return floor(Re($sum)+0.5); } + + use Test::More tests => 18; ok mo(2) == -1, "test for 2"; ok mo(5) == -1, "Example 1"; |
