in reply to Re: Prime Iterator
in thread Prime Iterator
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.
|
---|