A Prime Number list generation PHP script

A prime number is defined as a number which can be only divisible by 1 and that number itself. That number cannot be divisible by any other number. So if we try to divide that number by any other number between one and that number , we will get a remainder. According to the prime number definition number one ( 1 ) wont consider as a primer number. The smallest primer number is 2 .

See is a list of primer number below 50
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,

Here is a sample PHP script program to create a list of prime numbers
In this example we are going to print first 20 prime numbers.

<?php
$count = 0 ;
$number = 2 ;
while ($count < 20 )
{
$div_count=0;
for ( $i=1;$i<=$number;$i++)
{
if (($number%$i)==0)
{
$div_count++;
}
}
if ($div_count<3)
{
echo $number." , ";
$count=$count+1;
}
$number=$number+1;
}
?>

Its output will be :

2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 ,

Logic of this program : We need first store the current number to a variable. And then we will find the remainder for each division of other numbers with the stored number using a loop. And we will increment a counter if remainder found zero. After all the division operations with other numbers we will check the total counter for the remainder. If its value greater than two means , that number can be divisible by some other number instead of 1 and that number itself.If its value less than three means , its a primer number.

Now look at another PHP script for generating a list of prime numbers below 100.

<?php
$number = 2 ;
while ($number < 100 )
{
$div_count=0;
for ( $i=1;$i<=$number;$i++)
{
if (($number%$i)==0)
{
$div_count++;
}
}
if ($div_count<3)
{
echo $number." , ";
}
$number=$number+1;
}
?>

Its output will be ;

2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ,

This not only the one method of logic to create Primer number series .. You can create the list other methods and loops in PHP.

2 thoughts on “A Prime Number list generation PHP script”

  1. The largest prime number is still unknown. various competitions and prize offerings are going on about that. Hope any of you will find using that logic and PHP program skills.

Comments are closed.

Exit mobile version