How to determine whether a number is prime in php?

青灯夜游
Release: 2023-02-26 13:48:01
Original
5541 people have browsed it

Prime numbers are also called prime numbers. A natural number greater than 1 that cannot be divided by other natural numbers except 1 and itself is called a prime number; otherwise it is called a composite number. (Note: 1 is not a prime number.) So how does PHP determine whether a number is prime? The following article will introduce it to you.

How to determine whether a number is prime in php?

Let’s introduce what are the three ways to determine prime numbers in php?

Method 1:

Basic method, - counting method.

$num = 7;$n = 0; //用于记录能被整除的个数 -- 计数
for($i = 1;$i <= $num; ++$i){    
    if($num % $i == 0){        
       $n++;
    }
}
if($n == 2){    
   echo "$num 是素数";
}else{    
   echo "$num 不是素数";
}
Copy after login

Method 2:

That is, when a number is equal to the product of two numbers, one of the numbers must be less than half of the number. Use break; as long as one of the numbers can be divided, the loop will end immediately. This reduces the number of loops and speeds up the process.

$num = 5;$flag = true;
for($i = 2;$i <= $num/2;++$i)
{    if($num % $i == 0)
    {        $flag = false;        break;
    }
}if($flag)
{    echo "$num 是素数";
}else{    echo "$num 不是素数";
}
Copy after login

Method 3:

Same as above, when the product of two numbers is equal to one number, then one of the numbers must be less than the square root of the number.

$num = 4;for($i = 2;$i<$num;++$i){    
     if($num % $i == 0){        
         echo "$num 不是素数";        
         break;
    }    
    if($i >= sqrt($num)){        
       echo "$num 是素数";        
       break;
    }
}
Copy after login

For more PHP related knowledge, please visit: PHP Chinese website!

The above is the detailed content of How to determine whether a number is prime in php?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!