From 1aaa837e874b2f613520ea21a20e563341e987ce Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Mon, 6 Jun 2022 00:29:59 +0200 Subject: Add solutions to 167: Circular Prime & Gamma Function by E. Choroba --- challenge-167/e-choroba/perl/ch-1.pl | 45 ++++++++++++++++++++++++++++++++++++ challenge-167/e-choroba/perl/ch-2.pl | 19 +++++++++++++++ 2 files changed, 64 insertions(+) create mode 100755 challenge-167/e-choroba/perl/ch-1.pl create mode 100755 challenge-167/e-choroba/perl/ch-2.pl diff --git a/challenge-167/e-choroba/perl/ch-1.pl b/challenge-167/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..c255908376 --- /dev/null +++ b/challenge-167/e-choroba/perl/ch-1.pl @@ -0,0 +1,45 @@ +#!/usr/bin/perl +use warnings; +use strict; + +use Math::Prime::Util qw{ next_prime is_prime }; + +sub is_circular { + my ($p) = @_; + my $c = $p; + + # Start from 2, we don't need to check the number itself. + for (2 .. length $p) { + substr $c, 0, 0, substr $c, -1, 1, ""; + return if $c < $p || ! is_prime($c); + } + return 1 +} + +sub circular_prime { + my ($tally, $min_digits) = @_; + my @primes; + my $from = '1' x $min_digits - 1; + my $p = next_prime($from); + while (@primes < $tally) { + push @primes, $p + if ($p < 10 || $p !~ /[024568]/) # This speeds the code slightly. + && is_circular($p); + $p = next_prime($p); + } + return \@primes +} + +use Test::More tests => 3; + +is_deeply circular_prime(10, 3), + [113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933], + 'Example'; + +is_deeply circular_prime(10, 1), + [2, 3, 5, 7, 11, 13, 17, 37, 79, 113], + 'Shorter CPs'; + +is_deeply circular_prime(1, 19), + [1111111111111111111], + 'Longer CP'; diff --git a/challenge-167/e-choroba/perl/ch-2.pl b/challenge-167/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..0de3775583 --- /dev/null +++ b/challenge-167/e-choroba/perl/ch-2.pl @@ -0,0 +1,19 @@ +#!/usr/bin/perl +use warnings; +use strict; + +use PDL; +use PDL::GSLSF::GAMMA; + +sub gamma { + unpdl((gsl_sf_gamma(shift))[0])->[0] +} + +use Test2::V0 qw{ is plan within }; +plan 3; + +my $TOLERANCE = 0.0100000000001; + +is gamma(3), within(1.99, $TOLERANCE); +is gamma(5), within(24); +is gamma(7), within(719.99, $TOLERANCE); -- cgit