From a4a8fbd0eb824b8a0bd7a50a747238356c46e511 Mon Sep 17 00:00:00 2001 From: Niels van Dijke Date: Tue, 11 Jan 2022 22:31:09 +0000 Subject: Task 1 & 2 --- challenge-147/perlboy1967/perl/ch-1.pl | 40 ++++++++++++++++++++++++ challenge-147/perlboy1967/perl/ch-2.pl | 56 ++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100755 challenge-147/perlboy1967/perl/ch-1.pl create mode 100755 challenge-147/perlboy1967/perl/ch-2.pl diff --git a/challenge-147/perlboy1967/perl/ch-1.pl b/challenge-147/perlboy1967/perl/ch-1.pl new file mode 100755 index 0000000000..2fbd74581f --- /dev/null +++ b/challenge-147/perlboy1967/perl/ch-1.pl @@ -0,0 +1,40 @@ +#!/bin/perl + +=pod + +The Weekly Challenge - 147 + - https://perlweeklychallenge.org/blog/perl-weekly-challenge-147/#TASK1 + +Author: Niels 'PerlBoy' van Dijke + +TASK #1 › Truncatable Prime +Submitted by: Mohammad S Anwar + +Write a script to generate first 20 left-truncatable prime numbers in base 10. + + || In number theory, a left-truncatable prime is a prime number which, in a + || given base, contains no 0, and if the leading left digit is successively + || removed, then all resulting numbers are primes. + +=cut + +use v5.16; + +use Math::Primality qw(next_prime); + +my @tPrimes; +my %primes; + +my $n = 1; +do { + $n = next_prime($n); + $primes{$n}++; + + if (index($n,0)<0) { + my $p = $n; + 1 while ($p =~ s#^.## && exists $primes{$p}); + push(@tPrimes,$n) if ($p eq ''); + } +} while (scalar @tPrimes < 20); + +printf "%s\n", join(',',@tPrimes); diff --git a/challenge-147/perlboy1967/perl/ch-2.pl b/challenge-147/perlboy1967/perl/ch-2.pl new file mode 100755 index 0000000000..9a96d111c4 --- /dev/null +++ b/challenge-147/perlboy1967/perl/ch-2.pl @@ -0,0 +1,56 @@ +#!/bin/perl + +=pod + +The Weekly Challenge - 147 + - https://perlweeklychallenge.org/blog/perl-weekly-challenge-147/#TASK2 + +Author: Niels 'PerlBoy' van Dijke + +TASK #2 › Pentagon Numbers +Submitted by: Mohammad S Anwar + +Write a sript to find the first pair of Pentagon Numbers whose sum and difference +are also a Pentagon Number. + + || Pentagon numbers can be defined as P(n) = n(3n - 1)/2. + + +=cut + +use v5.16; + +sub pentagonNumber($) { + $_[0]*(3*$_[0]-1) >> 1; +} + +my @p = (undef); +my %pIdx; + +my $i = 1; + +while (1) { + push(@p,pentagonNumber scalar @p); + $pIdx{$p[-1]} = scalar @p - 1; + + foreach my $j (1 .. $i-1) { + my $dif = $p[$i] - $p[$j]; + next if !exists $pIdx{$dif}; + + my $sum = $p[$i] + $p[$j]; + + while ($p[-1] <= $sum) { + push(@p,pentagonNumber scalar @p); + $pIdx{$p[-1]} = scalar @p - 1; + } + + if (exists $pIdx{$sum}) { + printf "P(%d) + P(%d) = %d + %d = %d = P(%d)\n", + $i, $j, $p[$i], $p[$j], $sum, $pIdx{$sum}; + printf "P(%d) - P(%d) = %d - %d = %d = P(%d)\n", + $i, $j, $p[$i], $p[$j], $dif, $pIdx{$dif}; + exit; + } + } + $i++; +} -- cgit