Hey, that looks pretty cool and I'll see what I can do to implement that, once I've worked out the math (it doesn't look too hard). In the meantime, here's a much faster version, easier to read version, based upon an article by merlyn.

#!/usr/bin/perl use warnings; use strict; use Data::Dumper; sub NEXT ($) { $_[0]->() } sub prime_iterator { my $num = 0; sub { do { $num++; } until is_prime($num); return $num; } } sub is_prime { my $guess = shift; for (my $divisor = 2; $divisor * $divisor <= $guess; $divisor++) { return unless $guess % $divisor; } return 1; } my $prime = prime_iterator; my @primes; push @primes => NEXT $prime for (1 .. shift || 10); print Dumper \@primes;

Cheers,
Ovid

Update: Here's a better "is_prime" function, based upon a code snippet provided in the link the greenback mentioned. This is twice as fast as the above function.

sub is_prime { my $guess = shift; # accidentally reversed next two lines. Thanks to petral for catch +ing that :) return 1 if $guess == 2; return unless $guess > 2 and $guess % 2; my $max = 1 + int $guess ** .5; for ( my $divisor = 3; $divisor < $max; $divisor += 2 ) { return unless $guess % $divisor; } return 1; }

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.


In reply to Re: Re: Prime Iterator by Ovid
in thread Prime Iterator by Ovid

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.