PHP uses function to determine whether a number is prime

(*-*)浩
Release: 2023-02-24 06:42:01
Original
4702 people have browsed it

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;;

?>
Copy after login

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!

Related labels:
php
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!