p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/)
-   BOOK: Beginning PHP 5.3 (http://p2p.wrox.com/book-beginning-php-5-3-527/)
-   -   Chapter 4 Exercise 1 (http://p2p.wrox.com/book-beginning-php-5-3/99073-chapter-4-exercise-1-a.html)

ajjp5o7 July 5th, 2016 10:40 AM

Chapter 4 Exercise 1
 
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 != ) echo ' class="alt" ' ?>>
<td><?php echo $num ?></td>
<td>
<?php 
    
if ($num%== ) {
        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 !=&& $num == 0) {
        echo 
"No";
    }        
$primeIterations ceil(sqrt($num));
for (
$divisor $divisor <= $primeIterations$divisor $divisor+) {
    if  ( 
$num%$divisor == 0) echo "Yes";
    else echo 
"No";
}
?>

</td>
</tr>
<?php ?>
</table>


<body>
</body>
</html>

Could anyone give me some input?
Thank you


All times are GMT -4. The time now is 06:11 PM.

Powered by vBulletin®
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
2013 John Wiley & Sons, Inc.