<?php
Header ("Content-type:text/html;charset=utf-8");//Set encoding format
The prime number is a positive integer divisible only by itself and 1, especially when we specify that 1 is not a prime number.
/* Method One:
Define a function to calculate the prime number
function Prime_number ($n)
{$c =0;//counter initialization
for ($i =1; $i <= $n; $i + +)
{
if ($n% $i ==0)
{
$c + +;
}
}
if ($c ==2)//If you can divide the number by only 1 or 2, then it is prime
{
echo $n. " Is the prime number ";
}else
{
echo $n. " Not a prime number ";
}
}
Prime_number (5); * *
/*
When a number is equal to the product of two numbers, then the two numbers must have a square root that is less than this number,
Another number must be greater than the square root of the number ($j <=sqrt ($i)), which means that when we find that the current number is divisible by a number smaller than his square root,
You don't have to divide another number that is larger than his square root ($i% $j), reduce the number of cycles, and make the algorithm more concise.
Method Two:
function Prime_number ($n)
{
for ($i =2; $i <= $n; $i + +)
{
for ($j =2; $j <=sqrt ($i); $j + +)//Determine the square root of the current number
{
if ($i% $j ==0)
{
Continue 2;//If it is not a prime number, jump out of the inner loop and continue from the outer loop
}
}
echo $i;
echo "<br/>";
}
}
Prime_number (100);//Print out the prime number within 100 */
/*
Method Three: Using the screening method to find prime numbers
First step: First of all, we identified 1 as a prime number, 0 is identified as a non-prime, assuming that the given n numbers are prime numbers, identified as 1
The second step: starting from the first number of filters, encountered the current number of multiples to change his multiple identifier to 0 (in 2, will be 4,6,8.
After the identification is finished, the second number repeats the first number of operations until the square root of N, the last identity is still 1 is the prime number (neither multiples)
*/
function Prime_number ($n) {
Array_fill: Fills an array with the given value
$arr =array_fill (2, $n -1,1);//fills a subscript from 2 (because 1 is not a prime or composite) starts with a total of $n-1 elements, an array of 1 values
for ($i =2; $i <=sqrt ($n), $i + +)//filter Range
{
if ($arr [$i]==1)
{
For ($j =2* $i; $j <= $n; $j + = $i)//Selected filter number
{
$arr [$j]=0;//the value of multiples of all filters is set to 0
}
}
}
$count = 0;
foreach ($arr as $key + $value) {//traversal array
if ($value ==1) {
echo $key. " Is the prime number "; The subscript with a value of 1 is the prime number
$count + +;
echo "<br>";
}
}
Echo $count;
}
Prime_number (100);
?>
Note: If there is an error, please point out, thank you!
How to find prime numbers in PHP