## prime numbers from 1 to 100

A number which can be only divisible by 1 and itself, Called prime number . It must be exactly 2 factors 1 and itself.

Example: 5 is prime number (It can be divided by 1 or itself(5) )

The smallest primer number is 2.

Now, Look at PHP code to generate Prime Number from 1 to 100.

``````<?php
\$number = 100;

for(\$i = 2;\$i<=\$number;\$i++)
{
\$isPrime = true;
// here you can replace (\$i/2) to sqrt(\$i) to optimised/minimized the Iteration of loop
for(\$j = 2;\$j <=(\$i/2); \$j++)
{
if(\$i % \$j == 0)
{
\$isPrime = false;
}
}
if(\$isPrime == true)
{
echo \$i." ";
}
}

?>``````

Let’s start to understand the logic.

• Defined the number till the prime number to be print ( here 100)
• Run the loop from 2 to 100 to find, all prime number in between.
• Define a flag isPrime and assign a value True by default (initially)
• Write inner for loop from 2 to (\$i/2). we checked \$i can be divided by \$j. if yes then we re-assign isPrime flag to False
• Finally, out side of inner loop. we checked isPrime flag is True if yes then we print \$i

## Let’s Understand by an example

2 & 3 are a prime number so that skip this . We take an example of 4.

When outer loop will execute then by default isPrime variable assign True value. When goes into inner then check the \$i % \$J == 0, if condition will be true then we will assign the isPrime to false, (here \$i = 4, and \$j = 2, because we have taken an example of 4 and inner loop initial value \$j = 2)

( % module operator always return remainder). So here condition will be true and will go inside the if condition and assign isPrime flag to False

When, We out from inner loop after the false condition (\$j <=(\$i/2)). then checked if isPrime == true then print \$i. But here isPrime assigned false. So 4 is not a prime number. so it will not print.

Note: here inner loop, condition till \$i/2, because of minimised Iteration. You can do squire root of \$i.