diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2019-07-07 19:26:57 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2019-07-07 19:26:57 +0100 |
| commit | fd810cf69b719d02b00dcfe65bf3d235188fee0a (patch) | |
| tree | 63dc2136ee5c04a8e7df553026ec3e77f95f3bad /challenge-015 | |
| parent | 7d7115313502c07c6b4f7feaed23d290a968b69b (diff) | |
| parent | 161a3c2352494cd4ac91a1cf64faa0d6093c4b37 (diff) | |
| download | perlweeklychallenge-club-fd810cf69b719d02b00dcfe65bf3d235188fee0a.tar.gz perlweeklychallenge-club-fd810cf69b719d02b00dcfe65bf3d235188fee0a.tar.bz2 perlweeklychallenge-club-fd810cf69b719d02b00dcfe65bf3d235188fee0a.zip | |
Merge pull request #347 from kianmeng/master
Challenge #1 answer
Diffstat (limited to 'challenge-015')
| -rw-r--r-- | challenge-015/kian-meng-ang/perl5/ch-1.pl | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/challenge-015/kian-meng-ang/perl5/ch-1.pl b/challenge-015/kian-meng-ang/perl5/ch-1.pl new file mode 100644 index 0000000000..8432da16e9 --- /dev/null +++ b/challenge-015/kian-meng-ang/perl5/ch-1.pl @@ -0,0 +1,60 @@ +#!/usr/bin/env perl +# vi:et:sw=4 ts=4 ft=perl + +use strict; +use warnings; +use utf8; +use feature qw(say); + +# Interestigly, both CPAN modules can be used interchangeably. +# use Math::Prime::Util qw(nth_prime next_prime prev_prime); +use ntheory qw(nth_prime next_prime prev_prime); + +# See https://en.wikipedia.org/wiki/Strong_prime +# See https://oeis.org/A051634 +# See https://oeis.org/A051635 +sub prime_type { + my ($prime) = @_; + + my $pprime = prev_prime($prime); + my $nprime = next_prime($prime); + + return 'strong' if ($prime > ($pprime + $nprime) / 2); + return 'weak' if ($prime < ($pprime + $nprime) / 2); +} + +sub nth_strong_primes { + my ($nth) = @_; + + my ($pos, @primes) = (2, ()); + while (scalar @primes < $nth) { + my $prime = nth_prime($pos); + push @primes, $prime if (prime_type($prime) eq 'strong'); + $pos++; + } + + return \@primes; +} + +sub nth_weak_primes { + my ($nth) = @_; + + my ($pos, @primes) = (2, ()); + while (scalar @primes < $nth) { + my $prime = nth_prime($pos); + push @primes, $prime if (prime_type($prime) eq 'weak'); + $pos++; + } + + return \@primes; +} + +say 'Strong primes: ' , join ', ', @{nth_strong_primes(10)}; +say 'Weak primes: ', join ', ', @{nth_weak_primes(10)}; + +1; + +__END__ +$ perl ch-1.pl +Strong primes: 11, 17, 29, 37, 41, 59, 67, 71, 79, 97 +Weak primes: 3, 7, 13, 19, 23, 31, 43, 47, 61, 73 |
