in reply to Re: Finding the next larger prime.
in thread Finding the next larger prime.
Some minor (possible) improvements:
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):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; } }
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.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;
|
|---|