aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCY Fung <fungcheokyin@gmail.com>2022-06-12 05:00:23 +0800
committerCY Fung <fungcheokyin@gmail.com>2022-06-12 05:00:23 +0800
commitca71189e5959ea925a05c5b4412a64e5d10efe96 (patch)
tree8c76ee61ec96bf3c079acc54c0f56a19bf333203
parent3cc61075c2564e35c4826d6431312e2b0dcf2179 (diff)
downloadperlweeklychallenge-club-ca71189e5959ea925a05c5b4412a64e5d10efe96.tar.gz
perlweeklychallenge-club-ca71189e5959ea925a05c5b4412a64e5d10efe96.tar.bz2
perlweeklychallenge-club-ca71189e5959ea925a05c5b4412a64e5d10efe96.zip
improve efficiency
-rw-r--r--challenge-168/cheok-yin-fung/perl/ch-2.pl24
1 files changed, 16 insertions, 8 deletions
diff --git a/challenge-168/cheok-yin-fung/perl/ch-2.pl b/challenge-168/cheok-yin-fung/perl/ch-2.pl
index 3289846cfe..7466f52b01 100644
--- a/challenge-168/cheok-yin-fung/perl/ch-2.pl
+++ b/challenge-168/cheok-yin-fung/perl/ch-2.pl
@@ -27,7 +27,7 @@ sub hp {
sub my_hp {
my $recur_depth = $_[1];
- die "Walk so far but still cannot get result. :(\n" if $recur_depth > 10;
+ die "Walk so far but still cannot get result. :(\n" if $recur_depth > 20;
my $num = $_[0];
if (is_prime($num) == 2) {
return $num;
@@ -35,27 +35,35 @@ sub my_hp {
my @factors = ();
my $p = 2;
- do {
+ while ($num != 1) {
if (!($num % $p)) {
push @factors, $p;
$num /= $p;
}
else {
- $p = next_prime($p); # CAN BE IMPROVED
+ $p = next_prime($p);
}
- } while ($num != 1);
+ if ($p > sqrt $num) {
+ push @factors, $num;
+ last;
+ }
+ }
my $nxt = (reduce { $a . $b } @factors);
say " $nxt";
return my_hp($nxt, ++$recur_depth);
}
-use Test::More tests => 5;
+use Test::More tests => 7;
# test data from OEIS
ok hp(10) == 773;
ok hp(24) == 331_319;
ok hp(32) == 241_271;
+ok hp(40) == 3314192745739;
+ok hp(44) == 22815088913;
ok hp(45) == 3_411_949;
+ok hp(8) == 3331113965338635107;
-ok hp(44) == 22815088913; # this test spends approx 0.5 min (on CY's laptop).
-
-# ok hp(40) == 3314192745739; # this test spends approx. 2 min.
+# time:
+# real 0m1.963s
+# user 0m1.946s
+# sys 0m0.016s