aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2022-05-31 21:10:00 +0100
committerGitHub <noreply@github.com>2022-05-31 21:10:00 +0100
commit2e03498d1c40661f77127ce7169a454fab367195 (patch)
tree3e4b84f9d705366db698f84f11ff8cddfef1f279
parent25c53d7686db38078f3db0a10c1f42d6f466b7a2 (diff)
parent3c1fd23153433ee89901f434d3aa1133f33d15c8 (diff)
downloadperlweeklychallenge-club-2e03498d1c40661f77127ce7169a454fab367195.tar.gz
perlweeklychallenge-club-2e03498d1c40661f77127ce7169a454fab367195.tar.bz2
perlweeklychallenge-club-2e03498d1c40661f77127ce7169a454fab367195.zip
Merge pull request #6184 from PerlBoy1967/branch-for-challenge-167
w167 - Task 1
-rwxr-xr-xchallenge-167/perlboy1967/perl/ch-1.pl64
1 files changed, 64 insertions, 0 deletions
diff --git a/challenge-167/perlboy1967/perl/ch-1.pl b/challenge-167/perlboy1967/perl/ch-1.pl
new file mode 100755
index 0000000000..4db68779d5
--- /dev/null
+++ b/challenge-167/perlboy1967/perl/ch-1.pl
@@ -0,0 +1,64 @@
+#!/bin/perl
+
+=pod
+
+The Weekly Challenge - 167
+ - https://theweeklychallenge.org/blog/perl-weekly-challenge-167/#TASK1
+
+Author: Niels 'PerlBoy' van Dijke
+
+Task 1: Circular Prime
+Submitted by: Mohammad S Anwar
+
+Write a script to find out first 10 circular primes having at least 3 digits (base 10).
+
+Please checkout wikipedia for more information.
+
+=cut
+
+use v5.16;
+
+use IO::File;
+use Math::Primality qw(next_prime);
+use Math::Prime::XS qw(is_prime);
+
+STDOUT->autoflush(1);
+
+my ($n, $p) = (0,0);
+
+# According to http://oeis.org/A016114
+# should the first 19 circular primes be doable
+while ($n < 19) {
+ $p = next_prime($p);
+ if (isCircularPrime($p)) {
+ say int($p); $n++;
+ }
+}
+
+sub isCircularPrime ($) {
+ my $p = $_[0];
+
+ state $circularPrimes = {};
+
+ # Below 10 are straight circular primes
+ if (length($p) == 1) {
+ $circularPrimes->{$p}++;
+ return 1;
+ }
+
+ # If the prime contains a '5' or becomes potentionally even
+ # it can't be a circular prime
+ return 0 if ($p =~ m#[024568]#);
+
+ my ($n, $len) = ($p, length($p) - 1);
+ for (1 .. $len) {
+ $n = substr($n,1).substr($n,0,1);
+ return 0 unless (!exists $circularPrimes->{$n} && is_prime($n));
+ }
+
+ $circularPrimes->{$p}++;
+
+ return 1;
+}
+
+