in reply to Re^7: Number functions.. primes (ugly code runs faster)
in thread Number functions I have lying around
i used a different regex (and precompiled in the bench program using qr'\d[245680]$'):perl -e "map {print qq($_ ) unless $_ =~/(2|4|5|6|8|0)$/ } @ARGV" 2 3 +5 7 11 13 17 19 23 29 37 3 7 11 13 17 19 23 29 37
About saving time skipping numbers ending with some fixed digit, as said, the regex solution is slower: with this code:perl -e "map {print qq($_ ) unless $_ =~/\d[245680]$/ } @ARGV" 2 3 5 7 + 11 13 17 19 23 29 37 2 3 5 7 11 13 17 19 23 29 37
use strict; use warnings; use Benchmark qw{ cmpthese }; my $skipper_regex = qr'\d[245680]$'; sub primes_original { my $n = shift; return if $n < 2; my @primes = (2); for my $i (3 .. $n) { my $sqrt = sqrt $i; my $notprime; for my $p (@primes) { last if $p > $sqrt; $notprime = 1, last if 0 == $i % $p; } push @primes, $i unless $notprime; } return @primes } sub primes_skipper { my $n = shift; return if $n < 2; my @primes = (2); for my $i (3 .. $n) { next if $i =~ $skipper_regex; my $sqrt = sqrt $i; my $notprime; for my $p (@primes) { last if $p > $sqrt; $notprime = 1, last if 0 == $i % $p; } push @primes, $i unless $notprime; } return @primes } ## sub primes_opt_till_11 { my $n = shift; return if $n < 2; my @primes = (2); for my $i (3 .. $n) { if($i > 2 || $i % 2 == 0){next} if($i > 3 || $i % 3 == 0){next} if($i > 5 || $i % 5 == 0){next} if($i > 7 || $i % 7 == 0){next} if($i > 11 || $i % 11 == 0){next} my $sqrt = sqrt $i; my $notprime; for my $p (@primes) { last if $p > $sqrt; $notprime = 1, last if 0 == $i % $p; } push @primes, $i unless $notprime; } return @primes } ## use Test::More tests => 1; is_deeply([primes_original(10000)], [primes_skipper(10000)], "same"); cmpthese(-10, { primes_original => 'primes_original (10000)', primes_skipper => 'primes_skipper (10000)', primes_opt_till_11 => 'primes_opt_till_11 (10000)', });
1..1 ok 1 - same Rate primes_skipper primes_original primes_o +pt_till_11 primes_skipper 33.5/s -- -35% + -94% primes_original 51.4/s 53% -- + -90% primes_opt_till_11 519/s 1448% 909% + --
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^9: Number functions.. primes (ugly code runs faster)
by Lady_Aleena (Priest) on Apr 08, 2015 at 19:02 UTC | |
by trippledubs (Deacon) on Apr 08, 2015 at 20:09 UTC | |
by choroba (Cardinal) on Apr 09, 2015 at 08:47 UTC |