Hello readers, in this article, we will discuss how to print/ display prime numbers upto 100 in PHP. This article covers the topic in PHP but the same concept can be used in other languages like C Language, JavaScript, etc.
Before going into the coding process, let’s understand what a prime number is.
Basically, any number which is only divisible by 1 and itself is known as a prime number. For example, the number 13 is a prime number because 13 is only divisible by 1 and 13 itself. There are many numbers from 1 to 100 which are actually prime. The numbers are as follows.
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
Now we know the basics about what prime number is, we can now move forward towards the program.
Contents
Algorithm To Print All Prime Numbers Upto 100 in PHP
In order to find the prime numbers we can use two loops first one will go from 1 to 100 and the second loop will go from 2 to the value of the first loop divided by two. And the loops will be nested loops. If the variable in the first loop is “i” and the second loop is “j”, in the first loop we write a condition so that it will iterate from 2 to 100 (because 1 is not a prime number) and in the second loop we will iterate “j” from 2 to i/2. And inside these nested loops, we will nest an if condition in which we will check if “i” is divided by “j” or not, as prime numbers are those which are not divisible by other numbers, we will know if it is divisible or not, and on the basis of the result, we will determine whether it is prime or composite.
Program to Print All Prime Numbers Upto 100 in PHP
<!-- WAP to display prime numbers upto 100 --> <?php for($i = 2; $i <=100; $i++){ $c = 0; for($j = 2; $j<=$i/2; $j++){ if($i%$j==0){ $c++; break; } } if($c == 0){ echo "$i <br>"; } } ?>
Here, in this program, we have a loop where we go from 2 to 100 and inside this loop, we have another loop where we go from 2 to the previous value divided by 2 so that we can check if the number is prime or not and on the basis of that we are rendering the output to the user.
Subscribe to our newsletter!