Write a program in PHP to print prime numbers between 1 and 100
belongs to collection: PHP Programming Exercises
All Answers
Prime Number Program using While Loop
The following code prints a list of prime numbers between 1 and 100 (that is, numbers not divisible by something other than 1 or the number itself) using a while loop.
<?php
$limit = 100;
$init = 2;
while(TRUE)
{
$div = 2;
if($init > $limit)
{
break;
}
while(TRUE)
{
if($div > sqrt($init))
{
echo $init." ";
break;
}
if($init % $div == 0)
{
break;
}
$div = $div + 1;
}
$init = $init + 1;
}
?>
Output of the above code
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
In the above code, we have two while loops. The inner while loop does the testing with each possible divisor. If the inner loop finds a divisor, the number is not prime, so it breaks out without printing anything, and if the testing gets as high as the square root of the number, we can assume that the number is prime. The outer loop works through all the numbers between 1 and 100. This loop is broken when we have reached the breaking point of numbers to test.
need an explanation for this answer? contact us directly to get an explanation for this answertotal answers (2)
Prime Number Program using For Loop
Here, we have created a function 'checkPrime()' to check whether the number is prime or not. We loop over the number range (1 to 100) and pass each as a parameter to the function to check whether a number is prime or not.
Output of the above code:
need an explanation for this answer? contact us directly to get an explanation for this answerPrime Numbers between 1 and 100 : 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