summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorJohn P. Linderman <jpl@research.att.com>2001-03-13 07:36:32 -0500
committerJarkko Hietaniemi <jhi@iki.fi>2001-03-13 22:41:21 +0000
commit0bee9efe6e3302b0bae554ca99f35705369270f2 (patch)
tree26b70e9a91aca38b5a9bcd72155c15c2dc368cdd /lib
parent9424a4449820db49abc5c85e5aaada034b78d25b (diff)
downloadperl-0bee9efe6e3302b0bae554ca99f35705369270f2.tar.gz
Re: [ID 20010309.004] my-variables lose values while goto'ing within a for(;;)-loop
Message-Id: <200103131736.MAA35615@raptor.research.att.com> A more correct prime finder. p4raw-id: //depot/perl@9132
Diffstat (limited to 'lib')
-rw-r--r--lib/Tie/SubstrHash.pm18
1 files changed, 13 insertions, 5 deletions
diff --git a/lib/Tie/SubstrHash.pm b/lib/Tie/SubstrHash.pm
index afe5d8dc25..cd1125eab8 100644
--- a/lib/Tie/SubstrHash.pm
+++ b/lib/Tie/SubstrHash.pm
@@ -183,21 +183,29 @@ sub ceil {
return $num;
}
+# See:
+#
+# http://www-groups.dcs.st-andrews.ac.uk/~history/HistTopics/Prime_numbers.html
+#
+
sub findgteprime { # find the smallest prime integer greater than or equal to
use integer;
-# It may be sufficient (and more efficient, IF IT IS CORRECT) to use
-# $max = 1 + int sqrt $num and calculate it once only, but is it correct?
-
my $num = ceil(shift);
return 2 if $num <= 2;
$num++ unless $num % 2;
+ my $i;
+ my $sqrtnum = int sqrt $num;
+ my $sqrtnumsquared = $sqrtnum * $sqrtnum;
NUM:
for (;; $num += 2) {
- my $max = int sqrt $num;
- for ($i = 3; $i <= $max; $i += 2) {
+ if ($sqrtnumsquared < $num) {
+ $sqrtnum++;
+ $sqrtnumsquared = $sqrtnum * $sqrtnum;
+ }
+ for ($i = 3; $i <= $sqrtnum; $i += 2) {
next NUM unless $num % $i;
}
return $num;