diff options
author | Guillermo Ramos | 2019-07-01 13:06:49 +0200 |
---|---|---|
committer | Guillermo Ramos | 2019-07-01 13:06:49 +0200 |
commit | a0ff2b4cde91f92c186634da16310724d3c9cf24 (patch) | |
tree | eccf52cd4263bb379a82e59a42da9a73d15d642b /015 | |
parent | 5291a4911d54dc65886532c13c0dd8aa27eb49b1 (diff) | |
download | perlweekly-a0ff2b4cde91f92c186634da16310724d3c9cf24.tar.gz |
[015#1]
Diffstat (limited to '015')
-rwxr-xr-x | 015/ch1.pl | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/015/ch1.pl b/015/ch1.pl new file mode 100755 index 0000000..c6cc4db --- /dev/null +++ b/015/ch1.pl @@ -0,0 +1,39 @@ +#!/usr/bin/env perl +# +# Write a script to generate first 10 strong and weak prime numbers. +# (https://en.wikipedia.org/wiki/Strong_prime) +################################################################################ + +use strict; +use warnings; + +use List::Util qw<any>; +use List::Util qw<max>; + +my $LIMIT = 10; + +# Already found strong/weak primes +my (@strong, @weak); + +# Last known prime; will be pushed to either @strong or @weak once the next +# prime is found and we can compare the closeness +my $last_prime = 2; + +while (@strong < $LIMIT || @weak < $LIMIT) { + # Find next prime + my $candidate = $last_prime+1; + $candidate++ while any { $candidate % $_ == 0 } @strong, @weak; + + # Now we know whether $last_prime is strong or not; push it correspondingly + my $max_prime = max($strong[-1] || 0, $weak[-1] || 0); + if ($candidate - $last_prime < $last_prime - ($max_prime || $last_prime)) { + push @strong, $last_prime; + } else { + push @weak, $last_prime; + } + + # Candidate becomes the last known prime + $last_prime = $candidate; +} + +print "Strong: @strong[0..$LIMIT-1]\nWeak: @weak[0..$LIMIT-1]\n"; |