in reply to Finding the next larger prime.

This may not be exactly what you want, but it should do the trick.

sub next_prime_iterator { my $num = shift; do { $num++ } until is_prime($num); return $num; } sub is_prime { my $guess = shift; 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; }

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re^2: Finding the next larger prime. (improve)
by tye (Sage) on Oct 30, 2003 at 17:17 UTC

    Some minor (possible) improvements:

    sub next_prime_iterator { my $num = shift(@_); return 3 if $num < 3; do { $num += 2 } until is_prime($num); return $num; } sub is_prime { my $guess = shift(@_); my $divisor = 3; my $quotient; while(1) { $quotient= $guess / $divisor; return 1 if $quotient < $divisor; return 0 if int($quotient) == $quotient; $divisor += 2; } }
    Note that using int($quotient) == $quotient made me worry that this wouldn't always work if $guess is very near the mantissa limit on your machine. But it turns out that Perl's % doesn't do any better there anyway (it does worse):
    my $x= 1+~0; $x *= 2 while $x != $x+1; $x /= 2; my $y= $x; for( 1..5 ) { $x++; print $x-$y, " ", $x%3, " ", $x/3-int($x/3), "; "; } print $/ __END__ 1 0 0.75; 2 0 0; 3 2 0.25; 4 2 0.75; 5 1 0;
    So the first numbers (1 2 3 4 5) show that Perl can handle those integers exactly. The second numbers (0 0 2 2 1) don't follow the pattern of 2 0 1 2 0 1 2 0 1 as they should so % is returning invalid results here. The third numbers (0.75 0 0.25 0.75 0) are following the correct pattern (something close to 0.66 0 0.33 0.66 0 0.33) so I trust my int($quotient) == $quotient test.

                    - tye