Count numbers in a given range whose count of prime factors is a Prime Number
Last Updated :
26 Jul, 2025
Given a 2D array Q[][] of size N * 2 representing queries of the form {L, R}. For each query, the task is to print the count of numbers in the range [L, R] with a count of prime factors equal to a prime number.
Examples:
Input: Q[][] = {{4, 8}, {30, 32}}
Output: 3 2
Explanation:
Query 1:
Prime factors of 4 = {2, 2} and count of prime factors = 2
Prime factors of 5 = {5} and count of prime factors = 1
Prime factors of 6 = {2, 3} and count of prime factors = 2
Prime factors of 7 = {7} and count of prime factors = 1
Prime factors of 8 = {2, 2, 2} and count of prime factors = 3
Therefore, the total count of numbers in the range [4, 8] having count of prime factors is a prime number is 3.
Query 2:
Prime factors of 30 = {2, 3, 5} and count of prime factors = 3
Prime factors of 31 = {31} and count of prime factors = 1
Prime factors of 32 = {2, 2, 2, 2, 2} and count of prime factors = 5
Therefore, the total count of numbers in the range [4, 8] having count of prime factors is a prime number is 2.
Input: Q[][] = {{7, 12}, {10, 99}}
Output: 4
Naive Approach: The simplest approach to solve this problem is to traverse all the numbers in the range [L, R], and for each number, check if the count of prime factors of the number is a prime number or not. If found to be true, increment the counter by 1. After traversing, print the value of counter for each query.
Time Complexity: O(|Q| * (max(arr[i][1] - arr[i][0] + 1)) * sqrt(max(arr[i][1]))
Auxiliary space: O (1)
Efficient Approach: To optimize the above approach the idea is to precompute the smallest prime factor of each number in the range [Li, Ri] using Sieve of Eratosthenes. Follow the steps below to solve the problem:
- Generate and store the smallest prime factor of each element using Sieve of Eratosthenes.
- Find the count of prime factors for each number in the range [Li, Ri] using the Sieve.
- For each number, check if the total count of prime factors is a prime number or not. If found to be true then increment the counter.
- Create a prefix sum array, say sum[], where sum[i] will store the sum of elements from the range [0, i] whose count of prime factors is a prime number.
- Finally, for each query, print the value sum[arr[i][1]] – sum[arr[i][0] - 1].
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 1001
// Function to find the smallest prime factor
// of all the numbers in range [0, MAX]
vector<int> sieve()
{
// Stores smallest prime factor of all
// the numbers in the range [0, MAX]
vector<int> spf(MAX);
// No smallest prime factor of
// 0 and 1 exists
spf[0] = spf[1] = -1;
// Traverse all the numbers
// in the range [1, MAX]
for (int i = 2; i < MAX; i++) {
// Update spf[i]
spf[i] = i;
}
// Update all the numbers whose
// smallest prime factor is 2
for (int i = 4; i < MAX; i = i + 2) {
spf[i] = 2;
}
// Traverse all the numbers in
// the range [1, sqrt(MAX)]
for (int i = 3; i * i < MAX; i++) {
// Check if i is a prime number
if (spf[i] == i) {
// Update all the numbers whose
// smallest prime factor is i
for (int j = i * i; j < MAX;
j = j + i) {
// Check if j is
// a prime number
if (spf[j] == j) {
spf[j] = i;
}
}
}
}
return spf;
}
// Function to find count of
// prime factor of num
int countFactors(vector<int>& spf, int num)
{
// Stores count of
// prime factor of num
int count = 0;
// Calculate count of
// prime factor
while (num > 1) {
// Update count
count++;
// Update num
num = num / spf[num];
}
return count;
}
// Function to precalculate the count of
// numbers in the range [0, i] whose count
// of prime factors is a prime number
vector<int> precalculateSum(vector<int>& spf)
{
// Stores the sum of all the numbers
// in the range[0, i] count of
// prime factor is a prime number
vector<int> sum(MAX);
// Update sum[0]
sum[0] = 0;
// Traverse all the numbers in
// the range [1, MAX]
for (int i = 1; i < MAX; i++) {
// Stores count of prime factor of i
int prime_factor
= countFactors(spf, i);
// If count of prime factor is
// a prime number
if (spf[prime_factor] == prime_factor) {
// Update sum[i]
sum[i] = sum[i - 1] + 1;
}
else {
// Update sum[i]
sum[i] = sum[i - 1];
}
}
return sum;
}
// Driver Code
int main()
{
// Stores smallest prime factor of all
// the numbers in the range [0, MAX]
vector<int> spf = sieve();
// Stores the sum of all the numbers
// in the range[0, i] count of
// prime factor is a prime number
vector<int> sum = precalculateSum(spf);
int Q[][2] = { { 4, 8 }, { 30, 32 } };
// int N = sizeof(Q) / sizeof(Q[0]);
for (int i = 0; i < 2; i++) {
cout << (sum[Q[i][1]] - sum[Q[i][0] - 1])
<< " ";
}
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
public static int MAX = 1001;
// Function to find the smallest prime factor
// of all the numbers in range [0, MAX]
public static int[] sieve()
{
// Stores smallest prime factor of all
// the numbers in the range [0, MAX]
int spf[] = new int[MAX];
// No smallest prime factor of
// 0 and 1 exists
spf[0] = spf[1] = -1;
// Traverse all the numbers
// in the range [1, MAX]
for(int i = 2; i < MAX; i++)
{
// Update spf[i]
spf[i] = i;
}
// Update all the numbers whose
// smallest prime factor is 2
for(int i = 4; i < MAX; i = i + 2)
{
spf[i] = 2;
}
// Traverse all the numbers in
// the range [1, sqrt(MAX)]
for(int i = 3; i * i < MAX; i++)
{
// Check if i is a prime number
if (spf[i] == i)
{
// Update all the numbers whose
// smallest prime factor is i
for(int j = i * i; j < MAX; j = j + i)
{
// Check if j is
// a prime number
if (spf[j] == j)
{
spf[j] = i;
}
}
}
}
return spf;
}
// Function to find count of
// prime factor of num
public static int countFactors(int spf[], int num)
{
// Stores count of
// prime factor of num
int count = 0;
// Calculate count of
// prime factor
while (num > 1)
{
// Update count
count++;
// Update num
num = num / spf[num];
}
return count;
}
// Function to precalculate the count of
// numbers in the range [0, i] whose count
// of prime factors is a prime number
public static int[] precalculateSum(int spf[])
{
// Stores the sum of all the numbers
// in the range[0, i] count of
// prime factor is a prime number
int sum[] = new int[MAX];
// Update sum[0]
sum[0] = 0;
// Traverse all the numbers in
// the range [1, MAX]
for(int i = 1; i < MAX; i++)
{
// Stores count of prime factor of i
int prime_factor = countFactors(spf, i);
// If count of prime factor is
// a prime number
if (spf[prime_factor] == prime_factor)
{
// Update sum[i]
sum[i] = sum[i - 1] + 1;
}
else
{
// Update sum[i]
sum[i] = sum[i - 1];
}
}
return sum;
}
// Driver code
public static void main(String[] args)
{
// Stores smallest prime factor of all
// the numbers in the range [0, MAX]
int spf[] = sieve();
// Stores the sum of all the numbers
// in the range[0, i] count of
// prime factor is a prime number
int sum[] = precalculateSum(spf);
int Q[][] = { { 4, 8 }, { 30, 32 } };
// int N = sizeof(Q) / sizeof(Q[0]);
for(int i = 0; i < 2; i++)
{
System.out.print((sum[Q[i][1]] -
sum[Q[i][0] - 1]) + " ");
}
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 program to implement
# the above approach
MAX = 1001
# Function to find the smallest
# prime factor of all the numbers
# in range [0, MAX]
def sieve():
# Stores smallest prime factor of all
# the numbers in the range [0, MAX]
global MAX
spf = [0] * MAX
# No smallest prime factor of
# 0 and 1 exists
spf[0] = spf[1] = -1
# Traverse all the numbers
# in the range [1, MAX]
for i in range(2, MAX):
# Update spf[i]
spf[i] = i
# Update all the numbers whose
# smallest prime factor is 2
for i in range(4, MAX, 2):
spf[i] = 2
# Traverse all the numbers in
# the range [1, sqrt(MAX)]
for i in range(3, MAX):
# Check if i is a prime number
if (spf[i] == i):
# Update all the numbers whose
# smallest prime factor is i
for j in range(i * i, MAX):
# Check if j is
# a prime number
if (spf[j] == j):
spf[j] = i
return spf
# Function to find count of
# prime factor of num
def countFactors(spf, num):
# Stores count of
# prime factor of num
count = 0
# Calculate count of
# prime factor
while (num > 1):
# Update count
count += 1
# Update num
num = num // spf[num]
return count
# Function to precalculate the count of
# numbers in the range [0, i] whose count
# of prime factors is a prime number
def precalculateSum(spf):
# Stores the sum of all the numbers
# in the range[0, i] count of
# prime factor is a prime number
sum = [0] * MAX
# Traverse all the numbers in
# the range [1, MAX]
for i in range(1, MAX):
# Stores count of prime factor of i
prime_factor = countFactors(spf, i)
# If count of prime factor is
# a prime number
if (spf[prime_factor] == prime_factor):
# Update sum[i]
sum[i] = sum[i - 1] + 1
else:
# Update sum[i]
sum[i] = sum[i - 1]
return sum
# Driver code
if __name__ == '__main__':
# Stores smallest prime factor of all
# the numbers in the range [0, MAX]
spf = sieve()
# Stores the sum of all the numbers
# in the range[0, i] count of
# prime factor is a prime number
sum = precalculateSum(spf)
Q = [ [ 4, 8 ], [ 30, 32 ] ]
sum[Q[0][1]] += 1
# N = sizeof(Q) / sizeof(Q[0]);
for i in range(0, 2):
print((sum[Q[i][1]] -
sum[Q[i][0]]), end = " ")
# This code is contributed by Princi Singh
C#
// C# program to implement
// the above approach
using System;
class GFG{
public static int MAX = 1001;
// Function to find the smallest
// prime factor of all the numbers
// in range [0, MAX]
public static int[] sieve()
{
// Stores smallest prime factor
// of all the numbers in the
// range [0, MAX]
int []spf = new int[MAX];
// No smallest prime factor
// of 0 and 1 exists
spf[0] = spf[1] = -1;
// Traverse all the numbers
// in the range [1, MAX]
for(int i = 2; i < MAX; i++)
{
// Update spf[i]
spf[i] = i;
}
// Update all the numbers whose
// smallest prime factor is 2
for(int i = 4; i < MAX; i = i + 2)
{
spf[i] = 2;
}
// Traverse all the numbers in
// the range [1, sqrt(MAX)]
for(int i = 3; i * i < MAX; i++)
{
// Check if i is a prime number
if (spf[i] == i)
{
// Update all the numbers
// whose smallest prime
// factor is i
for(int j = i * i;
j < MAX; j = j + i)
{
// Check if j is
// a prime number
if (spf[j] == j)
{
spf[j] = i;
}
}
}
}
return spf;
}
// Function to find count of
// prime factor of num
public static int countFactors(int []spf,
int num)
{
// Stores count of
// prime factor of num
int count = 0;
// Calculate count of
// prime factor
while (num > 1)
{
// Update count
count++;
// Update num
num = num / spf[num];
}
return count;
}
// Function to precalculate the count of
// numbers in the range [0, i] whose count
// of prime factors is a prime number
public static int[] precalculateSum(int []spf)
{
// Stores the sum of all the numbers
// in the range[0, i] count of
// prime factor is a prime number
int []sum = new int[MAX];
// Update sum[0]
sum[0] = 0;
// Traverse all the numbers in
// the range [1, MAX]
for(int i = 1; i < MAX; i++)
{
// Stores count of prime factor of i
int prime_factor = countFactors(spf, i);
// If count of prime factor is
// a prime number
if (spf[prime_factor] == prime_factor)
{
// Update sum[i]
sum[i] = sum[i - 1] + 1;
}
else
{
// Update sum[i]
sum[i] = sum[i - 1];
}
}
return sum;
}
// Driver code
public static void Main(String[] args)
{
// Stores smallest prime factor
// of all the numbers in the
// range [0, MAX]
int []spf = sieve();
// Stores the sum of all the
// numbers in the range[0, i]
// count of prime factor is a
// prime number
int []sum = precalculateSum(spf);
int [,]Q = {{4, 8}, {30, 32}};
// int N = sizeof(Q) / sizeof(Q[0]);
for(int i = 0; i < 2; i++)
{
Console.Write((sum[Q[i, 1]] -
sum[Q[i, 0] - 1]) +
" ");
}
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript program to implement
// the above approach
let MAX = 1001
// Function to find the smallest prime factor
// of all the numbers in range [0, MAX]
function sieve()
{
// Stores smallest prime factor of all
// the numbers in the range [0, MAX]
let spf = new Array(MAX);
// No smallest prime factor of
// 0 and 1 exists
spf[0] = spf[1] = -1;
// Traverse all the numbers
// in the range [1, MAX]
for (let i = 2; i < MAX; i++) {
// Update spf[i]
spf[i] = i;
}
// Update all the numbers whose
// smallest prime factor is 2
for (let i = 4; i < MAX; i = i + 2) {
spf[i] = 2;
}
// Traverse all the numbers in
// the range [1, sqrt(MAX)]
for (let i = 3; i * i < MAX; i++) {
// Check if i is a prime number
if (spf[i] == i) {
// Update all the numbers whose
// smallest prime factor is i
for (let j = i * i; j < MAX;
j = j + i) {
// Check if j is
// a prime number
if (spf[j] == j) {
spf[j] = i;
}
}
}
}
return spf;
}
// Function to find count of
// prime factor of num
function countFactors(spf, num)
{
// Stores count of
// prime factor of num
let count = 0;
// Calculate count of
// prime factor
while (num > 1) {
// Update count
count++;
// Update num
num = num / spf[num];
}
return count;
}
// Function to precalculate the count of
// numbers in the range [0, i] whose count
// of prime factors is a prime number
function precalculateSum(spf)
{
// Stores the sum of all the numbers
// in the range[0, i] count of
// prime factor is a prime number
let sum = new Array(MAX);
// Update sum[0]
sum[0] = 0;
// Traverse all the numbers in
// the range [1, MAX]
for (let i = 1; i < MAX; i++) {
// Stores count of prime factor of i
let prime_factor
= countFactors(spf, i);
// If count of prime factor is
// a prime number
if (spf[prime_factor] == prime_factor) {
// Update sum[i]
sum[i] = sum[i - 1] + 1;
}
else {
// Update sum[i]
sum[i] = sum[i - 1];
}
}
return sum;
}
// Driver Code
// Stores smallest prime factor of all
// the numbers in the range [0, MAX]
let spf = sieve();
// Stores the sum of all the numbers
// in the range[0, i] count of
// prime factor is a prime number
let sum = precalculateSum(spf);
let Q = [ [ 4, 8 ], [ 30, 32 ] ];
// let N = sizeof(Q) / sizeof(Q[0]);
for (let i = 0; i < 2; i++) {
document.write((sum[Q[i][1]] - sum[Q[i][0] - 1]) +
" ");
}
// This code is contributed by gfgking
</script>
Time Complexity: O(|Q| + (MAX *log(log(MAX))))
Auxiliary Space: O(MAX)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem