aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordrbaggy <js5@sanger.ac.uk>2021-10-05 09:40:50 +0100
committerdrbaggy <js5@sanger.ac.uk>2021-10-05 09:40:50 +0100
commit98c56a4c993224ea7f5651bf4f7b26300bedbae7 (patch)
tree627ed8c1488627b374c067c2d1f49ac228598d2b
parentb6cea43d6eed00c7a023d2bbcad4186730173b86 (diff)
downloadperlweeklychallenge-club-98c56a4c993224ea7f5651bf4f7b26300bedbae7.tar.gz
perlweeklychallenge-club-98c56a4c993224ea7f5651bf4f7b26300bedbae7.tar.bz2
perlweeklychallenge-club-98c56a4c993224ea7f5651bf4f7b26300bedbae7.zip
pushing changes to use arrays and better names
-rw-r--r--challenge-133/james-smith/perl/ch-2.pl22
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++;
}