$_=~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:
- I simplified your if-prime expression.
- I removed the non-special case of "2".
- I simplified the loop and the regexp into a simple assignment.
- I exit the loop early (via last) when appropriate.
- I pluralized @prime to @primes.
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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.