#!/usr/bin/perl # prints all prime numbers up to the value of the command line argumen +t, or 500 if no args; use strict; use warnings; use POSIX; # for ceil() my @primes = ( 1, 2 ); # prime the list of primes :-) my $max = shift || 500; # initialise $max if no command line argument my $enough = ceil ( $max ** 0.5 ); # we only need to filter until we have >= the sqrt sub sieve { # create a new closure to act as a part of the sieve # the number that this closure will filter out multiples of my $divisor = shift; my $sieve_ref; return sub { my $number = shift; # Does $number divide by divisor? # If so, it's not prime, so bail out; return unless $number % $divisor; # if we have already created a next sieve, # then let it deal with the number # pass $number to it, and return; if ( $sieve_ref ){ &$sieve_ref( $number ); return }; #if we get this far, we have a new prime # if we need to make a new sieve to filter,do so $sieve_ref = sieve( $number ) if $number < $enough; # push the prime onto the array push @primes, $number; }; }; # the main program my $sieve = sieve( 2 ); # initialise &$sieve( $_ ) for 3 .. $max; print "The primes less than or equal to $max are @primes\n";

In reply to Sieve of Eratosthenes with closures by thinker

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.