Home  >  Article  >  Backend Development  >  PHP uses function to determine whether a number is prime

PHP uses function to determine whether a number is prime

(*-*)浩
(*-*)浩Original
2019-09-16 09:57:584712browse

Prime numbers are also called prime numbers. A natural number greater than 1 that is not divisible by other natural numbers except 1 and itself is called a prime number.

PHP uses function to determine whether a number is prime

First of all, know what a prime number is, a natural number greater than 1, the conditions for a number that cannot be divisible by other natural numbers except 1 and itself, To determine whether the number is prime. (Recommended learning: PHP programming from entry to proficiency)

<?php
// 判断一个数是否是素数,利用该函数的功能,求出1-200之间的所有素数
function suShu($x)
{
    $count = 0;
    for ($i = 1; $i <= $x; $i++) //循环
    {
        if ($x % $i == 0) { //取余
            $count++;
        }
    }
    if ($count == 2) { //取余等于2为true,否则为false
        return true;
    }
    return false;
}

$count = 0;
for ($i = 1; $i <= 200; $i++) //输出1-200之间的素数
{
    if (suShu($i)) {
        echo $i . &#39;1&#39;;
        $count++;
    }
}
echo &#39;<br>&#39;;
echo &#39;一共有&#39; . $i . &#39;个素数&#39;;

?>

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

Statement:
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