your image

PHP Prime Number Program - javatpoint

javapoint
Related Topic
:- PHP computer programming Java

Prime Number

A number which is only divisible by 1 and itself is called prime number. Numbers 2, 3, 5, 7, 11, 13, 17, etc. are prime numbers.

  • 2 is the only even prime number.
  • It is a natural number greater than 1 and so 0 and 1 are not prime numbers.

Prime number in PHP

Example:

Here is the Program to list the first 15 prime numbers.

  1. <?php  
  2. $count = 0;  
  3. $num = 2;  
  4. while ($count < 15 )  
  5. {  
  6. $div_count=0;  
  7. for ( $i=1; $i<=$num; $i++)  
  8. {  
  9. if (($num%$i)==0)  
  10. {  
  11. $div_count++;  
  12. }  
  13. }  
  14. if ($div_count<3)  
  15. {  
  16. echo $num." , ";  
  17. $count=$count+1;  
  18. }  
  19. $num=$num+1;  
  20. }  
  21. ?>  

Output:

 

8. Modules and PHP Abstract class | Build a CMS using OOP PHP CMS tutorial MVC [2020]

Prime Number using Form in PHP

Example:

We'll show a form, which will check whether a number is prime or not.

  1. <form method="post">  
  2. Enter a Number: <input type="text" name="input"><br><br>  
  3. <input type="submit" name="submit" value="Submit">  
  4. </form>  
  5. <?php  
  6. if($_POST)  
  7. {  
  8.     $input=$_POST['input'];  
  9.     for ($i = 2; $i <= $input-1; $i++) {  
  10.       if ($input % $i == 0) {  
  11.       $value= True;  
  12.       }  
  13. }  
  14. if (isset($value) && $value) {  
  15.      echo 'The Number '. $input . ' is not prime';  
  16. }  else {  
  17.    echo 'The Number '. $input . ' is prime';  
  18.    }   
  19. }  
  20. ?>  

Output:

On entering number 12, we get the following output. It states that 12 is not a prime number.

On entering number 97, we get the following output. It states that 97 is a prime number.

Comments