Php Program to Count Primes in Ranges
Last Updated :
13 Jan, 2022
Given a range [L, R], we need to find the count of total numbers of prime numbers in the range [L, R] where 0 <= L <= R < 10000. Consider that there are a large number of queries for different ranges.
Examples:Â
Â
Input : Query 1 : L = 1, R = 10
Query 2 : L = 5, R = 10
Output : 4
2
Explanation
Primes in the range L = 1 to R = 10 are
{2, 3, 5, 7}. Therefore for query, answer
is 4 {2, 3, 5, 7}.
For the second query, answer is 2 {5, 7}.
Â
A simple solution is to do the following for every query [L, R]. Traverse from L to R, check if current number is prime. If yes, increment the count. Finally, return the count.
An efficient solution is to use Sieve of Eratosthenes to find all primes up to the given limit. Then we compute a prefix array to store counts till every value before limit. Once we have a prefix array, we can answer queries in O(1) time. We just need to return prefix[R] – prefix[L-1].Â
Â
PHP
<?php
$MAX = 10000;
$prefix = array_fill (0, ( $MAX + 1), 0);
function buildPrefix()
{
global $MAX , $prefix ;
$prime = array_fill (0, ( $MAX + 1), true);
for ( $p = 2;
$p * $p <= $MAX ; $p ++)
{
if ( $prime [ $p ] == true)
{
for ( $i = $p * 2;
$i <= $MAX ; $i += $p )
$prime [ $i ] = false;
}
}
for ( $p = 2; $p <= $MAX ; $p ++)
{
$prefix [ $p ] = $prefix [ $p - 1];
if ( $prime [ $p ])
$prefix [ $p ]++;
}
}
function query( $L , $R )
{
global $prefix ;
return $prefix [ $R ] -
$prefix [ $L - 1];
}
buildPrefix();
$L = 5;
$R = 10;
echo query( $L , $R ) . "
";
$L = 1;
$R = 10;
echo query( $L , $R ) . "
";
?>
|
Output:Â Â
2
4
Please refer complete article on Count Primes in Ranges for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...