in reply to What am I missing?

That's not a "Sieve of Eratosthenes". You're testing with all the numbers between 2 and the square root of the max. Eratosthenes was smarter than that. He knew only to test with the primes. The primes you're generating.

Anyway, your problem is that you remove the prime itself from @n. Don't do that.

my $max = shift || 100; my @nums = (2 .. $max); my @primes; while (@nums) { my $prime = shift @nums; push @primes, $prime; if ($prime ** 2 > $max) { push @primes, @nums; last; } @nums = grep {$_ % $prime != 0} @nums; } say "@primes";

Replies are listed 'Best First'.
Re^2: What am I missing?
by neo_ (Novice) on Aug 11, 2009 at 16:22 UTC
    Much thanks to all for their helpful hints. I have learned from this thread.