[EMAIL PROTECTED] wrote: 
> Another list (discussing ICON) got me to:
> http://www.bagley.org/~doug/shootout/
> 
> and checking on perl's results found it sort of in
the > middle. 
> http://www.bagley.org/~doug/shootout/lang/perl/
> 
> This was one of the scripts:

Given the criteria for that test, there is little you
can do to improve it, since it must follow as closely
as possible the C program given.

Now, if you're looking for a speedup, that's a
different question.

In my early Perl years I once stole a golfish solution
of this off the NG from an Abigail post, and sped it
up by making some obvious improvements. 

For example, in the Sieve mentioned above, every prime
number found is used to sieve the numbers above it,
starting with twice that prime. With real numbers,
suppose we've just found that 17 is prime. The SoE
then checks 2*17=34, 3*17=51, etc., to see if they've
been removed from the list yet. 

But we know that all multiples of 17 have already been
removed up to, but not including, 17*17.

At any rate, here's my script. It could probably be
speeded up some more -- maybe someone would like to
take a shot at it?

#!perl
#
# modified Sieve of Eratosthenes, counts primes
# first argument is highest number to check
# second argument non-zero prints out all primes found

use integer;

# first prime, last number to check for priime
my ( $prime, $last ) = ( 2, ( shift or 50 ) );

# switch to print out list of primes
my $list = ( shift or 0 ); 

# initialize sieve, index 0 = number 0
my @sieve = ( 0, 0, map { 1 } ( $prime .. $last ) );

$sieve[ $last+1 ] = -1; # stop flag
 
while ( ( $product = $prime * $prime ) <= $last )
{
  # mark all multiples
  do { $sieve[ $product ] = 0; } while ( ( $product +=
$prime ) <= $last );

  # find next prime
  do { $prime++ } until $sieve[ $prime ]; # stop flag
will end "do" loop
}

if ( $list )
{
  map { print "$_ " if $sieve[ $_ ] } ( 0 .. $last );
  print "\n";
}

map { $count++ if $sieve[ $_ ] } ( 0 .. $last );

print "Count: $count\n";

__END__


__________________________________________________
Do You Yahoo!?
Yahoo! - Official partner of 2002 FIFA World Cup
http://fifaworldcup.yahoo.com

Reply via email to