#!/usr/local/bin/perl 
# $Id: sieve.perl,v 1.10 2001/05/06 04:37:45 doug Exp $
# http://www.bagley.org/~doug/shootout/

use strict;
use integer;

# Tony Bowden suggested using 0..8192 to create the array
# and to test for defined instead of the value.

my $NUM = $ARGV[0];
$NUM = 1 if ($NUM < 1);
my $count;
my @flags = ();
while ($NUM--) {
    $count = 0; 
    my @flags = (0 .. 8192);
    for my $i (2 .. 8192 ) {
        next unless defined $flags[$i];
        # remove all multiples of prime: i
        for (my $k=$i+$i; $k <= 8192; $k+=$i) {
            undef $flags[$k];
        }
        $count++;
    }
}
print "Count: $count\n";