From 145c060ad7ea5fa2221caae47382fe1207986add Mon Sep 17 00:00:00 2001 From: drbaggy Date: Wed, 15 Jun 2022 07:06:08 +0100 Subject: use factor_exp rather than factor as avoids the hash stage --- challenge-169/james-smith/perl/ch-2.pl | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/challenge-169/james-smith/perl/ch-2.pl b/challenge-169/james-smith/perl/ch-2.pl index fd49e07cc0..a694061493 100644 --- a/challenge-169/james-smith/perl/ch-2.pl +++ b/challenge-169/james-smith/perl/ch-2.pl @@ -4,23 +4,19 @@ use strict; use warnings; use feature qw(say); -use Math::Prime::Util qw(factor gcd); +use Math::Prime::Util qw(factor_exp gcd); use Time::HiRes qw(time); my $time = time; open my $fh, '>', 'achilles.txt'; -for( my( $n, $c, $MAX ) = ( 2, 0, @ARGV ? $ARGV[0] : 1e2 ); $c<$MAX; $n++ ) { +for( my( $n, $c, $MAX, @f ) = ( 2, 0, @ARGV ? $ARGV[0] : 1e2 ); $c<$MAX; $n++ ) { ## Factorise $n into prime factors, and count for each factor... ## ## e.g. 10800 has factors ( 2, 2, 2, 2, 3, 3, 3, 5, 5 ) or 2^4 3^3 5^2 ## - ## So %factors = ( 2 => 4, 3 => 3, 5 => 2 ); - ## - - my %factors; - $factors{$_}++ for factor $n; + ## factor_exp returns a list of tuples - [ prime, exponent ] ## If any of the values in this hash are 1 then we skip to the next number ## as it isn't brilliant.. @@ -35,11 +31,8 @@ for( my( $n, $c, $MAX ) = ( 2, 0, @ARGV ? $ARGV[0] : 1e2 ); $c<$MAX; $n++ ) { ## factorisation. say {$fh} sprintf '%6d: %15d = %s', ++$c, $n, - join ' . ', - map { "$_^$factors{$_}" } - sort { $a <=> $b } - keys %factors - if 1 == gcd grep { $_ < 2 ? next : 1 } values %factors + join ' . ', map { "$_->[0]^$_->[1]" } @f + if 1 == gcd map { $_->[1] < 2 ? next : $_->[1] } @f = factor_exp $n; ## Any of the factors is not squared we try the next number in the loop! ## The `next` out of grep jumps to the next loop of the foor loop... -- cgit