Prime numbers are having only two factors, one is 1 and other one is the number itself.
These are the first 5 prime numbers 2, 3, 5, 7, 11
Prime numbers are divisible by exactly two natural numbers, 1 and the number itself.
Checking and listing all prime numbers in PHP by using loop and form to take user inputs
Checking numbers
Any number we can check if it is Prime number or not .
$n1=18;
$flag=0;
for($i=2;$i<=($n1/2); $i++){
if($n1%$i == 0 ){
$flag=1;
break;
}
}
if($flag==0){
echo "$n1 is a prime number " ;
}else{
echo "$n1 is NOT a prime number " ;
}
Output
18 is NOT a prime number
Inside the if condition check we userd break; to come out of the for loop. This is a better way of coding as there is no need to check further if any one of the reminder of division ( or modulus ) became 0.
Sticky form to take user input
We will ask user to enter any number in a sticky form and then display the number is prime number or not. is a prime number
$n1=$_POST['n1']; // change this number
echo "<form method=POST action=''>
<input type=text name=n1 value='$n1'>
<input type=Submit value=submit></form>";
$flag=0;
for($i=2;$i<=($n1/2); $i++){
if($n1%$i == 0 ){
$flag=1;
break;
}
}
if($flag==0){
echo "$n1 is a prime number " ;
}else{
echo "$n1 is NOT a prime number " ;
}
Listing all prime numbers
We will loop through a range of numbers and check and list of all the prime numbers. ( All prime numbers less than 100 )