aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCY Fung <fungcheokyin@gmail.com>2022-06-12 06:10:22 +0800
committerCY Fung <fungcheokyin@gmail.com>2022-06-12 06:10:22 +0800
commit87a49e0dde51ea6a342eaecef8820bf0b3bc5ead (patch)
tree2c7f2ba4c9b2fcba0180a1f18029163a23afe180
parenteb043eb2670bd851f4f237961dc12036927fc570 (diff)
downloadperlweeklychallenge-club-87a49e0dde51ea6a342eaecef8820bf0b3bc5ead.tar.gz
perlweeklychallenge-club-87a49e0dde51ea6a342eaecef8820bf0b3bc5ead.tar.bz2
perlweeklychallenge-club-87a49e0dde51ea6a342eaecef8820bf0b3bc5ead.zip
finalize Task 1
-rw-r--r--challenge-168/cheok-yin-fung/perl/ch-2.pl46
1 files changed, 19 insertions, 27 deletions
diff --git a/challenge-168/cheok-yin-fung/perl/ch-2.pl b/challenge-168/cheok-yin-fung/perl/ch-2.pl
index 0f08ab3dc4..3e16406fbd 100644
--- a/challenge-168/cheok-yin-fung/perl/ch-2.pl
+++ b/challenge-168/cheok-yin-fung/perl/ch-2.pl
@@ -1,5 +1,3 @@
-# CAN BE IMPROVED
-
#!/usr/bin/perl
# The Weekly Challenge 168
# Task 2 Home Prime
@@ -7,14 +5,10 @@
use v5.24.0;
use warnings;
use List::Util qw/reduce/;
-use Math::BigInt::GMP; # [remark]
-use Math::BigInt::Pari; # [remark]
-use Math::Prime::Util::GMP qw/is_prime next_prime/;
-use bigint try => 'GMP,Pari'; # [remark]
-# remark: follow suggestions on POD of Math::Prime::Util
-
+use Math::Prime::Util qw/is_prime next_prime/;
+use Math::BigInt;
-say hp($ARGV[0]) if defined($ARGV[0]);
+say hp($ARGV[0]) if defined($ARGV[0]) && $ARGV[0] != 1;
@@ -27,8 +21,14 @@ sub hp {
sub my_hp {
my $recur_depth = $_[1];
+ die "Number involed too large.\n"
+ if
+ Math::BigInt->new(18446744073709551616) # 2**64
+ ->bcmp( Math::BigInt->new($_[0]) )
+ == -1;
+
die "Walk so far but still cannot get result. :(\n" if $recur_depth > 20;
- my $num = Math::BigInt->new($_[0]);
+ my $num = $_[0];
if (is_prime($num) == 2) {
return $num;
}
@@ -36,27 +36,23 @@ sub my_hp {
my @factors = ();
my $p = 2;
while ($num != 1) {
- my $temp_num = $num;
- if ( $num->bmod($p) == 0 ) {
- say $p;
+ if (!($num % $p)) {
push @factors, $p;
- $num = $num->bdiv($p);
+ $num /= $p;
}
else {
$p = next_prime($p);
}
- if ($p > $temp_num->bsqrt()) {
+ if ($p > sqrt $num) {
push @factors, $num;
last;
}
}
- my $nxt = join "", @factors;
+ my $nxt = (reduce { $a . $b } @factors);
say " $nxt";
return my_hp($nxt, ++$recur_depth);
}
-
-=pod
use Test::More tests => 8;
# test data from OEIS
ok hp(10) == 773;
@@ -65,16 +61,12 @@ ok hp(32) == 241_271;
ok hp(40) == 3314192745739;
ok hp(44) == 22815088913;
ok hp(45) == 3_411_949;
+
+# bigger cases;
ok hp( 8) == 3331113965338635107;
-ok hp(48) == 6161791591356884791277;
+ok hp(20) == 3318308475676071413;
-# time without the last hp(48) test case:
-# real 0m1.963s
-# user 0m1.946s
+# real 0m5.553s
+# user 0m5.535s
# sys 0m0.016s
-#
-# time without the last hp(48) test case and use simply Math::Prime::Util :
-# real 0m0.133s
-# user 0m0.115s
-# sys 0m0.011s