Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: Sieve of Eratosthenes with closures

by hdb (Monsignor)
on May 16, 2018 at 11:06 UTC ( #1214638=note: print w/replies, xml ) Need Help??

in reply to Sieve of Eratosthenes with closures

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...

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1214638]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2022-05-24 17:54 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (84 votes). Check out past polls.