This is a great idea. I always wanted to implement a sieve that can just go on finding new primes, i.e. without specifying a maximum up to which the sieving will be conducted. This would require not only to store the primes up to a point but also kind of the largest multiple of each prime up to that point. Also, I think using the modulus operator % violates the sieving philosophy. I never was able to make it work as I got confused keeping the primes and the multiples.
Using closures is ideal for that. Every time one finds a new prime, one generates a new sifter that is responsible for that prime and to store the progress to date. Here is my formulation:
use strict;
use warnings;
sub sifter {
my $p = shift;
my $c = $p;
return sub { $c += $p while $c < $_[0]; return $c-$_[0]; }
}
my @sieves;
my $n = 1;
loop: while( $n++ ){
$_->( $n ) or next loop for @sieves;
push @sieves, sifter( $n );
print "$n\n";
}
Clearly this is not a fast algorithm to find primes but I liked the idea...
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|