That's not a very good benchmark, as you will be pushing the answer onto the same array over and over again. After running your benchmark, @main::sol contains 28200 elements.

I don't understand why you are using our all over your program. What's wrong with my?

But you missed a much faster solution: just taking the squares of the numbers from 1 to the square root of 20_000.

Here's a revised benchmark:

use strict; use warnings; my (@sol1, @sol2, @sol3); my $lights = 20_000; sub sol1 { #init; my @lit = (1) x ($lights+1); #flip; for (2..($lights+1)) { my $cnt = $_; while ($cnt <= $lights) { $lit[$cnt] = !$lit[$cnt]; $cnt+=$_; } } #answer; @sol1 = grep {$lit[$_]} 1 .. ($lights+1); } sub sol2 { @sol2 = (); for (1..$lights) { my $sqr = sqrt($_); push @sol2, $_ if int($sqr) == $sqr; } } sub sol3 { @sol3 = map {$_**2} 1 .. sqrt($lights); } use Benchmark ':all'; cmpthese( -10, { sol1 => \&sol1, sol2 => \&sol2, sol3 => \&sol3, }); __END__ Rate sol1 sol2 sol3 sol1 3.92/s -- -90% -100% sol2 41.0/s 945% -- -99% sol3 3762/s 95923% 9085% --
Perl --((8:>*

In reply to Re^2: CarTalk Puzzler by Perl Mouse
in thread CarTalk Puzzler by freddo411

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.