diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2021-10-05 09:49:08 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-10-05 09:49:08 +0100 |
| commit | 094c94073e190dd28504ffccfc49b5a6a80f83cc (patch) | |
| tree | 8e22bd485e51e9d2f70c13b3d7cc76eb42b39b87 | |
| parent | dc184493d46a70942cef4dff4e7a539d46290a77 (diff) | |
| parent | 98c56a4c993224ea7f5651bf4f7b26300bedbae7 (diff) | |
| download | perlweeklychallenge-club-094c94073e190dd28504ffccfc49b5a6a80f83cc.tar.gz perlweeklychallenge-club-094c94073e190dd28504ffccfc49b5a6a80f83cc.tar.bz2 perlweeklychallenge-club-094c94073e190dd28504ffccfc49b5a6a80f83cc.zip | |
Merge pull request #4972 from drbaggy/master
Sorry one more - pushing changes to use arrays and better names
| -rw-r--r-- | challenge-133/james-smith/perl/ch-2.pl | 22 |
1 files changed, 13 insertions, 9 deletions
diff --git a/challenge-133/james-smith/perl/ch-2.pl b/challenge-133/james-smith/perl/ch-2.pl index 1f07513985..24616a3b82 100644 --- a/challenge-133/james-smith/perl/ch-2.pl +++ b/challenge-133/james-smith/perl/ch-2.pl @@ -5,7 +5,7 @@ use strict; use warnings; use feature qw(say); -my(%comp,@primes); ## Caches of digit sums of factors of $N +my(@sum_pf,@primes); ## Caches of digit sums of factors of $N say $_ foreach smith_numbers(@ARGV?$ARGV[0]:100); @@ -16,19 +16,21 @@ sub sum_prime_factors { my $N = shift; ## If we are composite then store the sum of the digit factors for the composite and return... - ( $N % $_) || ( return $comp{$N} = $comp{$N/$_} + $comp{$_} ) foreach @primes; + ( $N % $_) || ( return $sum_pf[$N] = $sum_pf[$N/$_] + $sum_pf[$_] ) + foreach @primes; ## Otherwise we are prime so add to primes and return nothing.... - $comp{$N} = sum_digits $N; + $sum_pf[$N] = sum_digits $N; push @primes, $N; return 0; ## Although we now the sum digits we return 0 as prime! } sub smith_numbers { ## This is the short form! using && - my ( $C, $n, @sn ) = (shift,1); + my ( $count, $n, @sn ) = (shift,1); + $sum_pf[ $count * 40 ] = 0; ## Pre-size array ( sum_digits( $n ) == sum_prime_factors $n ) && ## Diff between sums of factors == 0 ( push @sn, $n ) && ## push - ( @sn == $C ) && ## check length & return... + ( @sn == $count ) && ## check length & return... ( return @sn ) while $n++; } @@ -38,16 +40,18 @@ sub cl_sum_digits { my $t = 0; $t+=$_ foreach split //, $_[0]; $t } sub cl_sum_prime_factors { my $N = shift; - ( $N % $_) || ( return $comp{$N} = $comp{$N/$_} + $comp{$_} ) foreach @primes; - $comp{$N} = cl_sum_digits $N; + ( $N % $_) || ( return $sum_pf[$N] = $sum_pf[$N/$_] + $sum_pf[$_] ) foreach @primes; + $sum_pf[$N] = cl_sum_digits $N; push @primes, $N; return 0; } + sub cl_smith_numbers { - my ( $C, $n, @sn ) = (shift,1); + my ( $count, $n, @sn ) = (shift,1); + $sum_pf[ $count * 40 ] = 0; ( cl_sum_digits( $n ) == cl_sum_prime_factors $n ) && ( push @sn, $n ) && - ( @sn == $C ) && + ( @sn == $count ) && ( return @sn ) while $n++; } |
