Given a range [L, R], the task is to find the numbers from the range which have the count of their divisors as even as well as prime.
Then, print the count of the numbers found. The values of L and R are less than 10^6 and L< R.
Input: L=3, R=9 Output: Count = 3 Explanation: The numbers are 3, 5, 7 Input : L=3, R=17 Output : Count: 6
- The only number that is prime, as well as even, is ‘2’.
- So, we need to find all the numbers within the given range that have exactly 2 divisors,
i.e. prime numbers.
A simple approach:
- Start a loop from ‘l’ to ‘r’ and check whether the number is prime(it will take more time for bigger range).
- If the number is prime then increment the count variable.
- At the end, print the value of count.
An efficient approach:
- We have to count the prime numbers in range [L, R].
- First, create a sieve which will help in determining whether the number is prime or not in O(1) time.
- Then, create a prefix array to store the count of prime numbers where, element at index ‘i’ holds the count of the prime numbers from ‘1’ to ‘i’.
- Now, if we want to find the count of prime numbers in range [L, R], the count will be (sum[R] – sum[L-1])
- Finally, print the result i.e. (sum[R] – sum[L-1])
Below is the implementation of the above approach:
# Python 3 implementation of the approach
MAX = 1000000
# stores whether the number is prime or not
prime = [True] * (MAX + 1)
# stores the count of prime numbers
# less than or equal to the index
sum =  * (MAX + 1)
# create the sieve
prime = False
p = 2
while p * p
- Sum of all prime divisors of all the numbers in range L-R
- Program to find count of numbers having odd number of divisors in given range
- Count numbers from range whose prime factors are only 2 and 3
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
- Queries for the difference between the count of composite and prime numbers in a given range
- Count numbers in a range having GCD of powers of prime factors equal to 1
- Count total divisors of A or B in a given range
- Find numbers with K odd divisors in a given range
- Find numbers with n-divisors in a given range
- Count elements in the given range which have maximum number of divisors
- Find the number of divisors of all numbers in the range [1, n]
- Count the numbers < N which have equal number of divisors as K
- Sum of all the prime numbers in a given range
- Prime numbers in a given range using STL | Set 2
- Print prime numbers in a given range using C++ STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.