From: John P. Linderman Date: Tue, 13 Mar 2001 12:36:32 +0000 (-0500) Subject: Re: [ID 20010309.004] my-variables lose values while goto'ing within a for(;;)-loop X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=0bee9efe6e3302b0bae554ca99f35705369270f2;p=p5sagit%2Fp5-mst-13.2.git 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 --- diff --git a/lib/Tie/SubstrHash.pm b/lib/Tie/SubstrHash.pm index afe5d8d..cd1125e 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;