In this article we’ll explore using PHP to calculate whether a given number is prime and then calculate & display all the primes between 0 and that number. For those who slept through math (like me) a prime number is a natural number only divisible by 1 and itself. This problem is excellent for computers because the easiest solution is to check every number between 2 and the number in question. The resulting program is a great example to demonstrate how to use recursive loops and build an array.
The complete source code for the example is available for download here.
The source code starts with the essential head components and then sets up the form.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
body {
font-family:Verdana, Geneva, sans-serif;
font-size: 11px;
}
.standard {
padding:5px 5px 0px 5px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Prime Numbers</title>
</head>
<body>
<div class="standard">
<form action="index.php" method="post">
<input type="text" name="number" id="number" value="7">
<input type="submit" name="submit" value="submit">
</form>
</div>
The next section of the code, which starts right under the form, includes a handful of establishing variables. Beneath the variables the code uses a simple if/then statement to test for the presence of the post variable, indicating the form was submitted. If the post variable is set the program transfers the value to a variable entitled ‘$number’ for further processing. Otherwise a default value is set, which I decided in this case would be 7. Notice this matches the default value for the input field?
<?php
$number = "";
$i = 2;
$status = "";
$message = "";
$list = "1,";
$ii = 2;
$istatus = "";
if (isset($_POST['number'])) {
$number = $_POST['number'];
}else{
$number = 7;
}
The next block of code contains the loop. However, before the loop can run it is important to ensure the value passed is less than 100,000. Without this check it would be easy for a user to enter a number so large the server would not be able to process it before the page timed out. The limit could probably be closer to a million and still work but it is unnecessary to take any chances or over-burden the server for the purposes of this lesson.
For the next couple of steps the code uses something called a ‘for’ loop. A for loop runs until the index ($i) reaches a certain value. It also increments the index on each pass. The proper syntax is:
for($i;$i<$number;$i++){
enter your code
}
There are actually two loops in the example, an inner and an outer. The outer loop’s first job is to determine if the number submitted through the form is prime or not. This is done by dividing it by every number between 2 and one digit less than the submitted number. If the result is a natural number, meaning a positive whole number without any decimals, the submitted number is therefore not prime. This is tested in PHP by using the function is_int which returns true if the number is natural. If this is the case the program adds a 1 to the status variable. Later the status variable is checked as equal to zero (prime) or anything other than zero (not prime).
The inner loop repeats the same process recursively over the current index number to determine if it is prime. If the answer is yes the prime number is appended to a comma separated list, which is creatively entitled ‘$list’ in the example. Later the program will convert $list to an array and output it as a table.
if($number > 100000) {
$message = "That number is too large";
} else {
echo(‘<div class="standard">The number you submitted is:’.$number.’</div>’);
for($i;$i<$number;$i++){
$temp = ($number/$i);
if(is_int($temp)){
$status .= 1;
}
$ii = 2;
$istatus = "";
for($ii;$ii<$i;$ii++){
$itemp = ($i/$ii);
if(is_int($itemp)){
$istatus .= 1;
}
}
if($istatus == 0) {
$list .= $i.",";
}
}
$list = rtrim($list, ",");
$result = count($list);
if($status == 0) {
$message = "<div class=standard>This number is prime</div>";
} else {
$message = "<div class=standard>This number is not prime</div>";
}
}
Notice the PHP function rtrim? Once the loop is complete it is necessary to remove the final trailing “,” from $list. Otherwise it will create an empty value later when we split the list up into an array. The final steps are to output our results. The next block of code shows how this is done.
echo($message."<div class=standard>The prime numbers between 0 and ".$number." are: </div>");
$splits = preg_split("[,]", $list);
$split_length = count($splits);
$ai = 1;
echo("<div><br><table cellpadding=5 border=1><tr>");
for($ai;$ai<$split_length;$ai++) {
echo("<td>".$splits[$ai]);
if(($ai>1) && ($ai%4) == 0) {echo("</td></tr>");}else{echo("</td>");}
}
echo("</tr></table></div>");
?>
</body>
</html>
After outputting the status of the submitted value the program uses a PHP array function called preg_split to convert the comma separated list of prime numbers to an array named $splits. Preg_split takes two arguments. The first one is a regular expression identifying where to split the string. In this case we want it split at each comma in the list so the first argument is [,]. The second argument is the the actual string to split.
Once the array is created there is one last ‘for’ loop over the prime numbers array that outputs each value to a table. The table employs the same modulus operator referenced in the last post to know when to create a new row.

No Comments »
No comments yet.
RSS feed for comments on this post. TrackBack URL
Leave a comment