The solution in the book to exercise 4.1 is a hard coded listing of prime numbers.
I'm trying to put together a function that determines if the number is prime and then echos "Yes" or "No".
Here is where I'm hosting the exercise:
http://ajjpreble.com/learning-php/exercise4-1.php
And Here is the code I've used:
PHP Code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="common.css" />
<title>Exercise 4.1</title>
<style type="text/css">
th { text-align: left; background-color: #999; }
th, td { padding:0.4em;}
tr.alt td { background: #ddd; }
</style>
</head>
<table>
<tr>
<th>Number</th>
<th>Parity</th>
<th>Prime</th>
</tr>
<?php
$iterations = 10;
for ($num = 1; $num <= $iterations; $num++ )
{
?>
<tr<?php if ( $num % 2 != 0 ) echo ' class="alt" ' ?>>
<td><?php echo $num ?></td>
<td>
<?php
if ($num%2 == 0 ) {
echo "Even";
}
else {
echo "Odd";
}
?>
</td>
<td>
<?php
//1 is not prime. See: [url]http://en.wikipedia.org/wiki/Prime_number#Primality_of_one[/url]
if($num == 1)
echo "No";
//2 is prime (the only even number that is prime)
if($num == 2)
echo "Yes";
/**
* if the number is divisible by two, then it's not prime and it's no longer
* needed to check other even numbers
*/
if($num !=2 && $num % 2 == 0) {
echo "No";
}
$primeIterations = ceil(sqrt($num));
for ($divisor = 3 ; $divisor <= $primeIterations; $divisor = $divisor+2 ) {
if ( $num%$divisor == 0) echo "Yes";
else echo "No";
}
?>
</td>
</tr>
<?php } ?>
</table>
<body>
</body>
</html>
Could anyone give me some input?
Thank you