in reply to Re: CarTalk Puzzler
in thread CarTalk Puzzler
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% --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: CarTalk Puzzler
by radiantmatrix (Parson) on Nov 17, 2005 at 17:54 UTC |