aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorStephen Lynn <bizlsg@localhost.localdomain>2022-07-21 17:57:44 +0800
committerStephen Lynn <bizlsg@localhost.localdomain>2022-07-21 17:57:44 +0800
commit875d5a2ca4e4be888a9041ef1c395e8316918b19 (patch)
treecee74b00e9b4bc853bdbeae4862cb213e381c8bb
parent89420388600f6dc1b23a09069d421d721bf293e5 (diff)
downloadperlweeklychallenge-club-875d5a2ca4e4be888a9041ef1c395e8316918b19.tar.gz
perlweeklychallenge-club-875d5a2ca4e4be888a9041ef1c395e8316918b19.tar.bz2
perlweeklychallenge-club-875d5a2ca4e4be888a9041ef1c395e8316918b19.zip
faster alt2-ch-1.pl
-rwxr-xr-xchallenge-174/steve-g-lynn/perl/alt2-ch-1.pl34
1 files changed, 34 insertions, 0 deletions
diff --git a/challenge-174/steve-g-lynn/perl/alt2-ch-1.pl b/challenge-174/steve-g-lynn/perl/alt2-ch-1.pl
new file mode 100755
index 0000000000..c58be4e80c
--- /dev/null
+++ b/challenge-174/steve-g-lynn/perl/alt2-ch-1.pl
@@ -0,0 +1,34 @@
+#!/usr/bin/env perl
+
+#real 0m1.660s
+#user 0m1.652s
+#sys 0m0.005s
+
+#faster algorithm.
+#See my blog: https://thiujiac.blogspot.com/2022/07/pwc-174.html
+
+for my $i (0 .. 9) { print "$i\n"; }
+for my $i (2 .. 650_000 ) { &disarium($i) && (print &disarium($i),"\n" ); }
+
+sub disarium {
+ #-- inputs
+ my ($n)=@_;
+ my (@nstr)=split(//,$n);
+ my @indx = 2..(scalar(@nstr)+1);
+ my $retval=0;
+
+ #-- calculate a^2+b^3+c^4 ... for $n=abc...
+ for my $i (0..(@nstr-1)) {
+ $retval += ($nstr[$i] ** $indx[$i]);
+ }
+
+ #check if $retval is divisible by 10^length($n)-1
+ my $x = (10 ** @nstr) - 1;
+
+ #if divisible construct and return disarium number
+ if ( ( ($retval-$n) % $x ) == 0 && (($retval-$n) > 0) ) {
+ return int( ($retval-$n)/$x ) . $n;
+ }
+ return undef;
+}
+