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

藏色散人
Release: 2023-04-05 15:22:02
Original
3702 people have browsed it

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;
    }
}
Copy after login

Output:

小于等于n的质数的个数为:168
Copy after login

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!

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