Thursday 27 January 2011

Calculate prime numbers using PHP

Simply create a file named primeNumberCalculator.php. Copy following text in it.

You need a web server supporting php scripting.
Place the file where your http web server see it. e.g: /var/www

Open the file in a web browser. e.g: http://localhost/primeNumberCalculator.php

<html>
<body>

<h2>PHP Prime number calculator</h2>
<form name="input" action="primeNumberCalculator.php" method="get">
How many primes?: <input type="text" name="count" />
<input type="submit" value="Submit" />
</form>
<?php

// How many prime numbers are we going to calculate:
$count=$_GET["count"];
if ($count == "") {
   $count = 10;  // Default value
}

// We show the first prime number:
$prime_array=array("2");
echo $prime_array[0];
echo " ";

$total=1; // prime number array length.
$number = 3; // current number we are going to test for primality.

$i=1; // We start with 1 because first prime is already printed.
while ( $i<$count ) {
   $index=0;
   $is_prime="true";
   $max = floor(sqrt($number));
   $n = $prime_array[$index];
   while(($n <= $max) && ($is_prime == "true")) {
      if (($number % $n) == 0) {
         $is_prime="false";
      }
      $index++;
      $n = $prime_array[$index];
   }
   if ($is_prime=="true") {
      echo " " . $number;
      $prime_array[$total] = $number;
      $total++;
      $i++;
   }

   $number += 2;
}

?>

</body>
</html>

0 comentarios: