This blog describes how to find prime numbers between 1 and
100 using PHP. Prime number is a number which is divided by 1 and itself. Consider the number 5. It is prime number
because it can be divided by 1 and 5.

### PHP program for prime numbers:

Consider the
below program which is used to find prime numbers from 1 to 100.

<?php

for($i = 1; $i <= 100; $i++)

$mm = 0;

for($j = 2; $j <= $i/2; $j++) {

//only not prime numbers

if ($i % $j == 0) {

$mm++;

break;

}

}

if ($mm == 0) {

echo"$i is prime number<br/>";

}

}

?>

for($i = 1; $i <= 100; $i++)

$mm = 0;

for($j = 2; $j <= $i/2; $j++) {

//only not prime numbers

if ($i % $j == 0) {

$mm++;

break;

}

}

if ($mm == 0) {

echo"$i is prime number<br/>";

}

}

?>

In above
program, if a number is divided by any number except 1 and itself, then it is
not prime number. Otherwise it is a prime number.

Now you got prime numbers between 1 and 100 using PHP.

**Related Post**

better optimisation is to search not to half of the number but to root of a number. There won't be any dividers later on

ReplyDeleteGMP gmp_nextprime ( int $a )

ReplyDeleteWhy not Sieve of Eratosthenes? It's more efficient:

ReplyDeletehttp://www.hashbangcode.com/blog/sieve-eratosthenes-php

This comment has been removed by the author.

ReplyDeleteMuch more efficient:

ReplyDelete<?php

function is_prime($num)

{

$max = (int)sqrt($num);

for($i = $max; $i >= 2; --$i)

{

if ($num % $i == 0)

{

return false;

}

}

return true;

}

// The function returns the correct value,

// but skippig them will enable skipping even numbers

echo"1 is prime number<br>2 is prime number<br>";

for($i = 3; $i <= 100; $i+=2)

{

if (is_prime($i))

{

echo"$i is prime number<br>";

}

}

1 is neither prime nor composite.

ReplyDelete