View Single Post
  #1 (permalink)  
Old July 5th, 2016, 11:40 AM
ajjp5o7 ajjp5o7 is offline
Registered User
Points: 5, Level: 1
Points: 5, Level: 1 Points: 5, Level: 1 Points: 5, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jul 2016
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default 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
Reply With Quote