3 ###############################################################################
5 ## Copyright (c) 1995 - 2004 by Steffen Beyer. ##
6 ## All rights reserved. ##
8 ## This program is free software; you can redistribute it ##
9 ## and/or modify it under the same terms as Perl itself. ##
11 ###############################################################################
14 use vars qw($limit $set $start $stop $min $max $norm $i $j);
18 print "\n***** Calculating Prime Numbers - The Sieve Of Erathostenes *****\n";
26 print "\nPlease enter an upper limit (>15): ";
28 if ($limit =~ /^\s*(\d+)\s*$/) { $limit = $1; } else { $limit = 0; }
35 print "\nRunning in batch mode - using $limit as upper limit.\n\n";
38 $set = Bit::Vector->new($limit+1);
40 print "Calculating the prime numbers in the range [2..$limit]...\n\n";
46 ## Alternative (slower!):
51 #for ( $j = 4; $j <= $limit; $j += 2 ) { $set->Bit_Off($j); }
52 #for ( $i = 3; ($j = $i * $i) <= $limit; $i += 2 )
54 # for ( ; $j <= $limit; $j += $i ) { $set->Bit_Off($j); }
65 print "Found $norm prime numbers in the range [2..$limit]:\n\n";
67 for ( $i = $min, $j = 0; $i <= $max; $i++ )
69 if ($set->contains($i)) { print "prime number #", ++$j, " = $i\n"; }
76 sub print_elapsed_time
79 my($sec,$min,$hour,$year,$yday) = (gmtime($stop - $start))[0,1,2,5,7];
81 print "Elapsed time: ";
84 printf("%d year%s ", $year, ($year!=1)?"s":"");
87 if (($yday > 0) || $flag)
89 printf("%d day%s ", $yday, ($yday!=1)?"s":"");
92 if (($hour > 0) || $flag)
94 printf("%d hour%s ", $hour, ($hour!=1)?"s":"");
97 if (($min > 0) || $flag)
99 printf("%d minute%s ", $min, ($min!=1)?"s":"");
101 printf("%d second%s.\n\n", $sec, ($sec!=1)?"s":"");