diff options
| author | E. Choroba <choroba@matfyz.cz> | 2022-01-03 15:43:58 +0100 |
|---|---|---|
| committer | E. Choroba <choroba@matfyz.cz> | 2022-01-03 15:43:58 +0100 |
| commit | 3073c81f90e278e68c650c2c3c6d59c46506c6a0 (patch) | |
| tree | 523affeb30eb8d6e70d3224644302ac1a3bb3185 | |
| parent | 41f8dae6667e8b4215b9f2507d7a2e14236890b9 (diff) | |
| download | perlweeklychallenge-club-3073c81f90e278e68c650c2c3c6d59c46506c6a0.tar.gz perlweeklychallenge-club-3073c81f90e278e68c650c2c3c6d59c46506c6a0.tar.bz2 perlweeklychallenge-club-3073c81f90e278e68c650c2c3c6d59c46506c6a0.zip | |
Add solutions to 146: 10001st Prime Number & Curious Fraction Tree
| -rwxr-xr-x | challenge-146/e-choroba/perl/ch-1.pl | 38 | ||||
| -rwxr-xr-x | challenge-146/e-choroba/perl/ch-2.pl | 29 |
2 files changed, 67 insertions, 0 deletions
diff --git a/challenge-146/e-choroba/perl/ch-1.pl b/challenge-146/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..44dfa7e285 --- /dev/null +++ b/challenge-146/e-choroba/perl/ch-1.pl @@ -0,0 +1,38 @@ +#!/usr/bin/perl +use warnings; +use strict; + +{ package Prime::Generator; + + sub new { bless [2, 3], shift } + + sub xth_prime { + my ($self, $x) = @_; + my $p = $self->[-1] + 2; + CANDIDATE: + while (@$self < $x) { + for my $q (@$self) { + next CANDIDATE if 0 == $p % $q; + + last if $q * $q > $p; # Optimisation. + } + push @$self, $p; + } continue { + $p += 2; + } + return $self->[ $x - 1 ] + } +} + +use Test2::V0; +plan 6; + +my $pg = 'Prime::Generator'->new; + +is $pg->xth_prime(1), 2, '1st prime = 2'; +is $pg->xth_prime(2), 3, '2nd prime = 3'; +is $pg->xth_prime(3), 5, '3rd prime = 5'; +is $pg->xth_prime(10), 29, '10th prime = 29'; +is $pg->xth_prime(5), 11, '5th prime (breaking the order) = 11'; + +is $pg->xth_prime(10001), 104743, '10001st Prime Number'; diff --git a/challenge-146/e-choroba/perl/ch-2.pl b/challenge-146/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..a9da5ef2c8 --- /dev/null +++ b/challenge-146/e-choroba/perl/ch-2.pl @@ -0,0 +1,29 @@ +#!/usr/bin/perl +use warnings; +use strict; + +# a/b +# / \ +# / \ +# a/(a+b) (a+b)/b + +sub parent { + my ($x, $y) = @_; + return $x < $y ? ($x, $y - $x) : ($x - $y, $y) +} + +sub grandparent { + return parent(parent(@_)) +} + +use Test2::V0; +plan 4; + +{ my $member = [3, 5]; + is [parent(@$member)], [3, 2], 'Example 1 parent'; + is [grandparent(@$member)], [1, 2], 'Example 1 grandparent'; +} +{ my $member = [4, 3]; + is [parent(@$member)], [1, 3], 'Example 2 parent'; + is [grandparent(@$member)], [1, 2], 'Example 2 grandparent'; +} |
