********* primes.cgi PERL code **********
#!/usr/bin/perl -w
use CGI ':standard';
my $limit;
my @primes;
print header;
print start_html('Prime numbers via Perl/CGI'),
h1('Prime numbers calculated by PERL/CGI script');
print start_form,
textfield('upperLimit', '300', '5', '5'),
"This program prints out all the prime numbers <= n ",
br,
"Enter an integer n as an upper limit: ",
p,
submit('Show Primes'),
end_form,
hr,
p;
$limit = param('upperLimit');
@primes = (0, 0, 2 .. $limit);
for (my $index = 2; $index <= sqrt($limit); $index++)
{
if ( $primes[$index] )
{
my $cross_out = $index * 2;
while ( $cross_out <= $limit )
{
$primes[$cross_out] = 0;
$cross_out += $index;
}
}
}
my $per_line = ($limit > 1000)? 15 : 18;
my $adjust = ($limit > 10000)? " " : "";
my $n = 0;
if (param())
{
print "\n
\n"; foreach my $prime_number ( @primes ) { if ( $prime_number ) { $n++; my $spaces = ""; if ($prime_number < 10) { $spaces .= " " . $adjust; } elsif ($prime_number < 100) { $spaces .= " " . $adjust; } elsif ($prime_number < 1000) { $spaces .= " " . $adjust; } elsif ($prime_number < 10000) { $spaces .= $adjust; } print "$spaces" . "$prime_number "; if ($n % $per_line == 0) { print "\n"; } } } print "\n\nThere are $n primes between 2 and $limit\n"; } print hr, p, "See the script of the ", a( {-href=>'showPrimesCode.cgi'}, "primes.cgi PERL/CGI statements"), ", which illustrates many techniques and strategies.", p, hr; ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); $year = $year + 1900; $nextMonth = $mon + 2; print "\n
\n" . `cal` . "\n\n" . `cal $nextMonth $year` . "\n\n"; # back tic for Unix command print end_html;