in reply to Primes. Again.
$_=~s/$i//; is converting some members of @prime into the zero-length string. The zero-length string gets interpreted as zero in a numerical context. It could be fixed by skipping blank lines as seen below.
I took the liberty of making a few optimizations:
my @primes; for my $i (2..100) { $primes[$i] = $i; foreach (@primes) { if ($_ && $i % $_ == 0) { $primes[$i] = ''; last; } } } foreach (@primes) { next unless $_; print "$_\n"; }
You could also avoid adding it in the first place, as shown in the following snippet.
my @primes; NUMBER: for my $i (2..100) { foreach (@primes) { if ($i % $_ == 0) { # Divides evenly, so not prime. next $NUMBER; } } push @primes, $i; } foreach (@primes) { print "$_\n"; }
The disadvantage of the latter is that you can't do if ($prime[$i]) to determine if $i is prime. The advantage is smaller memory usage and a (presumably) small increase in speed.
Update: Cleaned up/Expanded the text.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
| A reply falls below the community's threshold of quality. You may see it by logging in. |