Advertisement
dimipan80

Find Primes in Range

Apr 22nd, 2015
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.43 KB | None | 0 0
  1. <!--Write a PHP script PrimesInRange.php that receives two numbers – start and end – from an input field and displays all numbers in that range as a comma-separated list. Prime numbers should be bolded. Styling the page is optional.-->
  2.  
  3. <!DOCTYPE html>
  4. <html>
  5. <head lang="en">
  6.     <meta charset="UTF-8"/>
  7.     <title>The Primes In Range</title>
  8.     <style type="text/css">
  9.         p {
  10.             font-size: 18px;
  11.             color: #555;
  12.         }
  13.  
  14.         strong {
  15.             font-weight: 800;
  16.             color: #000;
  17.         }
  18.     </style>
  19. </head>
  20. <body>
  21. <form method="post">
  22.     <p>
  23.         <label for="number-min">Starting Index:</label>
  24.         <input type="number" name="start" id="number-min" min="1" required/>
  25.         <label for="number-max">End:</label>
  26.         <input type="number" name="end" id="number-max" min="2" required/>
  27.         <input type="submit" value="Submit"/>
  28.     </p>
  29. </form>
  30. <p>
  31.     <?php
  32.     if (!array_key_exists('start', $_POST) || !array_key_exists('end', $_POST) ||
  33.         (int)$_POST['start'] >= (int)$_POST['end']
  34.     ) {
  35.         die('The Input Data is OUT of Range or Form is Empty!!!');
  36.     }
  37.  
  38.     $start = (int)$_POST['start'];
  39.     $end = (int)$_POST['end'];
  40.     for ($i = $start; $i <= $end; $i++) {
  41.         $isPrime = true;
  42.         $maxDivider = (int)sqrt($i);
  43.         for ($j = 2; $j <= $maxDivider; $j++) {
  44.             if (($i % $j) === 0) {
  45.                 $isPrime = false;
  46.                 break;
  47.             }
  48.         }
  49.  
  50.         if ($isPrime) {
  51.             echo "<strong>$i</strong>";
  52.         } else {
  53.             echo $i;
  54.         }
  55.  
  56.         if ($i < $end) {
  57.             echo ', ';
  58.         }
  59.     }
  60.     ?>
  61. </p>
  62. </body>
  63. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement