Home >Backend Development >PHP Tutorial >How to calculate the total number of prime numbers in a specified area in PHP?

How to calculate the total number of prime numbers in a specified area in PHP?

藏色散人
藏色散人Original
2019-03-13 10:52:083755browse

In the previous article "How to use PHP to calculate the sum of prime numbers less than 100? ", we introduced to you the method of calculating the sum of prime numbers using PHP. I believe you have some understanding of the judgment of prime numbers. So if we want to get all the prime numbers in a certain integer range, how to achieve it?

How to calculate the total number of prime numbers in a specified area in PHP?

For example, if we want to calculate the number of all prime numbers in n, the range of n is 1≤n≤9999,999.

Now we will introduce to you PHP’s method of calculating the total number of prime numbers in a specified area:

The code is as follows:

<?php
$max = 1000000;

// 初始化数组
for ($i = 0; $i <$max; $i ++) {
    $array [$i] = 1;
}
$array [1] = 0;

// 由于0和1不是素数,从2开始判断
for ($i = 2; $i<$max; $i ++) {
    if ($array [$i] === 0)
        continue;
    else
    {
        For ($j = $i * $i; $j<$max; $j += $i) {
            $array [$j] = 0;
        }
    }

    for ($i = 2; $i <$max; $i ++) {
        $array [$i] += $array [$i-1];
    }

    While (1) {
        $res = fscanf(STDIN, &#39;%d&#39;, $n);
        if ($res == 0) break;

        $cnt = $array [$n];
        echo "小于等于n的质数的个数为: ";
        echo $cnt.PHP_EOL;
    }
}

Output:

小于等于n的质数的个数为:168

Note: Prime numbers are also called prime numbers, and there are infinite numbers. A prime number is defined as a natural number greater than 1 that has no other factors except 1 and itself.

Related recommendations: "PHP Tutorial"

This article is an introduction to the method of calculating the total number of prime numbers in a specified area in PHP. I hope it will be helpful to friends who need it. help!

The above is the detailed content of How to calculate the total number of prime numbers in a specified area in PHP?. 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