Hello Lady_Aleena,

You are correct, and by eliminating even numbers up front, along with multiples of five, choroba’s solution can be speeded up by around a third:

#! perl use strict; use warnings; use Benchmark 'cmpthese'; use Test::More tests => 1; use constant MAX => 1e4; sub primes_choroba { 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_eliminate { my $n = shift; return if $n < 2; my @primes = (2, 3, 5); for (my $i = 7; $i <= $n; $i += 2) { next if 0 == $i % 5; 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 } is_deeply ( [ primes_choroba (MAX) ], [ primes_eliminate(MAX) ], 'same' ); cmpthese ( -10, { choroba => 'primes_choroba (MAX)', eliminate => 'primes_eliminate(MAX)', } );

Output:

17:20 >perl 1208_SoPW.pl 1..1 ok 1 - same Rate choroba eliminate choroba 64.3/s -- -26% eliminate 86.6/s 35% -- 17:20 >

But note that choroba’s solution is well over a hundred times faster than the non-sieve method you posted, so maybe an additional speedup of around 35% was irrelevant to the point he was making. :-)

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re^10: Number functions.. primes (ugly code runs faster) by Athanasius
in thread Number functions I have lying around by Lady_Aleena

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.