diff options
| -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++; } |
