Along with Perl, PHP is the new workhorse of the web. At this time, PHP tends to predominate, at least if the number of free scripts available on the web is any guide.
PHP is one of those many languages based on C/C++, as you can plainly see. This code runs under Apache/PHP5. Although PHP can run as a standalone language, this script was designed to be used in a web-server environment. Thus it generates a web page rather than standard console output.
When retrieving the source file, please note that the php extension has been disabled by adding a .txt suffix to the file. To run it in a server environment, the .txt suffix must be removed.
<?php
//////////////////////////////////////////////////////////
// Name: Peter M. Maurer
// Program: Sieve of Eratosthenes
// Due: Never
// Language: PHP
//////////////////////////////////////////////////////////
echo "<html>\n";
echo "\n";
echo "<head>\n";
echo " <title>Sieve</title>\n";
echo "</head>\n";
echo "\n";
echo "<body>\n";
echo "\n";
for ($i=0 ; $i<1000 ; $i++)
{
// everything is potentially prime until proven otherwise
$Candidates[$i] = 1;
}
// Neither 1 nor 0 is prime, so flag them off
$Candidates[0] = 0;
$Candidates[1] = 0;
// start the sieve with the integer 0
$i = 0;
while ($i<1000)
{
// advance to the next un-crossed out number.
// this number must be a prime
while ($i<1000 && $Candidates[$i] == 0)
{
$i++;
}
// insure against running off the end of the data structure
if ($i<1000)
{
// cross out all multiples of the prime, starting with 2*p.
for ($j=2 ; $j*$i < 1000 ; $j++)
{
$Candidates[$j*$i] = 0;
}
// advance to the next candidate
$i++;
}
}
// all uncrossed-out numbers are prime (and only those numbers)
// echo all primes
echo "<p>Primes less than 1000\n";
for ($i=0 ; $i<1000 ; $i++)
{
if ($Candidates[$i] != 0)
{
echo "<br>",$i," is prime\n";
}
}
echo "\n";
echo "</body>\n";
echo "\n";
echo "</html>\n";
echo "\n";
?>