foreach my $n ( @ARGV ? @ARGV : (20, 48, 96, 7, 69, 33, 13195, 600851475143, 2147483647) ) {
####
perl pm1194192.pl 18 54 27000 29474100
Number: 18 , Prime_Factors: => 2 3 3
Number: 54 , Prime_Factors: => 2 3 9
Number: 27000 , Prime_Factors: => 2 2 2 3 5 9 25
Number: 29474100 , Prime_Factors: => 2 2 3 5 15 32749
####
#!/usr/bin/perl
use warnings;
use strict;
########
my $doSqrt; if($ARGV[0] eq '--sqrt') {$doSqrt = shift @ARGV;} # added to toggle whether or not I do the sqrt after ever num
sub prime_factors {
my $num = shift;
my @primes = ();
my $max = sqrt($num);
while ($num % 2 == 0) {
push @primes, 2;
$num /= 2;
}
foreach (my $i = 3; $i <= $max; $i += 2) {
if ($num % $i == 0) {
push @primes, $i;
$num /= $i;
$max = sqrt($num) if $doSqrt; # added by [pryrt]
redo; # changed from [id://1194102], where it used to be: next;
}
}
if ($num > 2) {
push @primes, $num;
}
return @primes;
}
foreach my $n ( @ARGV ? @ARGV : (20, 48, 96, 7, 69, 33, 13195, 600851475143, 2147483647) ) {
my @result = prime_factors($n);
print "Number: $n , Prime_Factors: => @result", "\n";
}
####
$ time perl pm1194192.pl 18 54 27000 29474100 3217491003
Number: 18 , Prime_Factors: => 2 3 3
Number: 54 , Prime_Factors: => 2 3 3 3
Number: 27000 , Prime_Factors: => 2 2 2 3 3 3 5 5 5
Number: 29474100 , Prime_Factors: => 2 2 3 3 5 5 32749
Number: 3217491003 , Prime_Factors: => 3 32749 32749
real 0m0.010s
user 0m0.008s
sys 0m0.000s
$ time perl pm1194192.pl --sqrt 18 54 27000 29474100 3217491003
Number: 18 , Prime_Factors: => 2 3 3
Number: 54 , Prime_Factors: => 2 3 3 3
Number: 27000 , Prime_Factors: => 2 2 2 3 3 3 5 5 5
Number: 29474100 , Prime_Factors: => 2 2 3 3 5 5 32749
Number: 3217491003 , Prime_Factors: => 3 32749 32749
real 0m0.008s
user 0m0.004s
sys 0m0.000s
####
...
my @list = (20, 48, 96, 7, 69, 33, 13195, 600851475143, 2147483647, 18, 54, 27000, 29474100, 589806);
foreach my $n ( @list ) {
my @result = prime_factors($n);
print "Number: $n , Prime_Factors: => @result", "\n";
}
use Benchmark qw(cmpthese);
cmpthese( -10, {
once => sub { prime_factors($_) for @list },
every => sub { prime_factors_sqrt($_) for @list },
});
__END__
...
Rate once every
once 16.9/s -- -94%
every 286/s 1593% --