Print Prime Numbers from 1 to 100 in PHP using For loop | While loop
Print prime numbers from 1 to 100 in PHP using for loop and while loop.
In this article, you will learn how to print prime numbers from 1 to 100 in PHP using for loop and while loop.
Example
------The prime numbers from 1 to 60 are------
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59
You should have knowledge of the following topics in PHP programming to understand this program:
- PHP For loop
- PHP While loop
Sample of Prime Numbers
In this article, we solve this problem using two methods:
- Using the for loop
- Using the while loop
Source Code
<?php
// Print Prime Numbers from 1 to 100 in PHP using For loop
$x = 60;
echo "------The prime numbers from 1 to ".$x." are------\n\n";
for ($i = 0; $i < $x; $i++) {
// There are niether prime nor composite if as skip 0 and 1 number
if ($i == 1 || $i == 0)
continue;
$f = 1;
for ($j = 2; $j < intval($i / 2) + 1; $j++) {
if ($i % $j == 0) {
$f = 0;
break;
}
}
// If f = 1 means i is prime number and f = 0 means i is not prime number
if ($f == 1)
echo $i." ";
}
echo "\n";
?>
Output
------The prime numbers from 1 to 60 are------
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59
Explanation
In this given program, we have taken input from the variable $x = 60
to generate prime numbers up to 60.
Then we applied simple calculation via for loop to check every number of range between 1-60 to find the prime numbers.
If any number is divided by only 1 & itself and which number is divisible by any numbers it means these type numbers are called prime numbers.
After the whole calculation, this will return these numbers: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59
, It's the final output of the above program.
Print Prime Numbers from 1 to 100 in PHP using While loop
<?php
// Print Prime Numbers from 1 to 100 in PHP using While loop
$x = 60;
echo "------The prime numbers from 1 to ".$x." are------\n\n";
$i = 0;
while ($i < $x) {
// There are niether prime nor composite if as skip 0 and 1 number
if ($i == 1 || $i == 0) {
$i++;
continue;
}
$f = 1;
$j = 2;
while ($j < intval($i / 2) + 1) {
if ($i % $j == 0) {
$f = 0;
break;
}
$j++;
}
// If f = 1 means i is prime number and f = 0 means i is not prime number
if ($f == 1)
echo $i." ";
$i++;
}
echo "\n";
?>