in reply to Primes. Again.
Your method of deleting from your @prime list is a bit suspect. First, a minor cleanup. I'm removing the special case for "2" - partly because of premature optimisation, and partly because I hate special cases. And I'm introducing a debugging aid: a print statement to tell us where we are.
Running this tells me that the problem happens when $i is 5. That's because during the $i == 4 loop, you've gone and set $prime[3] from 4 to "" (removing the "4"). Instead, what you really want to do is not bother to push $i onto @prime unless you know it already to be prime:use strict; use warnings; my @prime = 2; for my $i(3..100){ print "$i...\n"; push @prime, $i; for(@prime){ if(int($i/$_)==($i/$_) and $i!=$_){ for(@prime){ $_=~s/$i//; } } } } for(@prime){ print "$_\n"; }
IMO, this is a perfect excuse to use List::MoreUtils' "any" function:use strict; use warnings; my @prime = 2; for my $i(3..100){ print "$i...\n"; my $is_prime = 1; for(@prime){ if(int($i/$_)==($i/$_) and $i!=$_){ $is_prime = 0; last; } } push @prime, $i if $is_prime; } for(@prime){ print "$_\n"; }
(Thanks again to borisz for pointing this out to me earlier.)use strict; use warnings; use List::MoreUtils qw/any/; my @prime = 2; for my $i(3..100){ push @prime, $i unless any { int($i/$_)==($i/$_) and $i!=$_ } @pri +me; } for(@prime){ print "$_\n"; }
I'm sure this can be optimised further (without drastic changes to your original algorithm), but I'll let you investigate this further.
|
|---|