Check if a number has prime count of divisors
Last Updated :
12 Jul, 2025
Given an integer N, the task is to check if the count of divisors of N is prime or not.
Examples:
Input: N = 13
Output: Yes
The divisor count is 2 (1 and 13) which is prime.
Input: N = 8
Output: No
The divisors are 1, 2, 4 and 8.
Approach: Please read this article to find the count of divisors of a number. So find the maximum value of i for every prime divisor p such that N % (pi) = 0. So the count of divisors gets multiplied by (i + 1). The count of divisors will be (i1 + 1) * (i2 + 1) * ... * (ik + 1).
It can now be seen that there can only be one prime divisor for the maximum i and if N % pi = 0 then (i + 1) should be prime. The primality can be checked in sqrt(n) time and the prime factors can also be found in sqrt(n) time. So the overall time complexity will be O(sqrt(n)).
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function that returns true
// if n is prime
bool Prime(int n)
{
// There is no prime
// less than 2
if (n < 2)
return false;
// Run a loop from 2 to sqrt(n)
for (int i = 2; i <= sqrt(n); i++)
// If there is any factor
if (n % i == 0)
return false;
return true;
}
// Function that returns true if n
// has a prime count of divisors
bool primeCountDivisors(int n)
{
if (n < 2)
return false;
// Find the prime factors
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0) {
// Find the maximum value of i for every
// prime divisor p such that n % (p^i) == 0
long a = n, c = 0;
while (a % i == 0) {
a /= i;
c++;
}
// If c+1 is a prime number and a = 1
if (a == 1 && Prime(c + 1))
return true;
// The number cannot have two factors
// to have count of divisors prime
else
return false;
}
// Else the number is prime so
// it has only two divisors
return true;
}
// Driver code
int main()
{
int n = 13;
if (primeCountDivisors(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function that returns true
// if n is prime
static boolean Prime(int n)
{
// There is no prime
// less than 2
if (n < 2)
return false;
// Run a loop from 2 to sqrt(n)
for (int i = 2; i <= (int)Math.sqrt(n); i++)
// If there is any factor
if (n % i == 0)
return false;
return true;
}
// Function that returns true if n
// has a prime count of divisors
static boolean primeCountDivisors(int n)
{
if (n < 2)
return false;
// Find the prime factors
for (int i = 2; i <= (int)Math.sqrt(n); i++)
if (n % i == 0)
{
// Find the maximum value of i for every
// prime divisor p such that n % (p^i) == 0
long a = n, c = 0;
while (a % i == 0)
{
a /= i;
c++;
}
// If c+1 is a prime number and a = 1
if (a == 1 && Prime((int)c + 1) == true)
return true;
// The number cannot have two factors
// to have count of divisors prime
else
return false;
}
// Else the number is prime so
// it has only two divisors
return true;
}
// Driver code
public static void main (String[] args)
{
int n = 13;
if (primeCountDivisors(n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
from math import sqrt
# Function that returns true
# if n is prime
def Prime(n) :
# There is no prime
# less than 2
if (n < 2) :
return False;
# Run a loop from 2 to sqrt(n)
for i in range(2, int(sqrt(n)) + 1) :
# If there is any factor
if (n % i == 0) :
return False;
return True;
# Function that returns true if n
# has a prime count of divisors
def primeCountDivisors(n) :
if (n < 2) :
return False;
# Find the prime factors
for i in range(2, int(sqrt(n)) + 1) :
if (n % i == 0) :
# Find the maximum value of i for every
# prime divisor p such that n % (p^i) == 0
a = n; c = 0;
while (a % i == 0) :
a //= i;
c += 1;
# If c + 1 is a prime number and a = 1
if (a == 1 and Prime(c + 1)) :
return True;
# The number cannot have two factors
# to have count of divisors prime
else :
return False;
# Else the number is prime so
# it has only two divisors
return True;
# Driver code
if __name__ == "__main__" :
n = 13;
if (primeCountDivisors(n)) :
print("Yes");
else :
print("No");
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function that returns true
// if n is prime
static bool Prime(int n)
{
// There is no prime
// less than 2
if (n < 2)
return false;
// Run a loop from 2 to sqrt(n)
for (int i = 2; i <= (int)Math.Sqrt(n); i++)
// If there is any factor
if (n % i == 0)
return false;
return true;
}
// Function that returns true if n
// has a prime count of divisors
static bool primeCountDivisors(int n)
{
if (n < 2)
return false;
// Find the prime factors
for (int i = 2; i <= (int)Math.Sqrt(n); i++)
if (n % i == 0)
{
// Find the maximum value of i for every
// prime divisor p such that n % (p^i) == 0
long a = n, c = 0;
while (a % i == 0)
{
a /= i;
c++;
}
// If c+1 is a prime number and a = 1
if (a == 1 && Prime((int)c + 1) == true)
return true;
// The number cannot have two factors
// to have count of divisors prime
else
return false;
}
// Else the number is prime so
// it has only two divisors
return true;
}
// Driver code
public static void Main()
{
int n = 13;
if (primeCountDivisors(n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by AnkitRai01
JavaScript
<script>
// Javascript implementation of the approach
// Function that returns true
// if n is prime
function Prime(n)
{
// There is no prime
// less than 2
if (n < 2)
return false;
// Run a loop from 2 to sqrt(n)
for(var i = 2; i <= Math.sqrt(n); i++)
// If there is any factor
if (n % i == 0)
return false;
return true;
}
// Function that returns true if n
// has a prime count of divisors
function primeCountDivisors( n)
{
if (n < 2)
return false;
// Find the prime factors
for(var i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0)
{
// Find the maximum value of i for every
// prime divisor p such that n % (p^i) == 0
var a = n, c = 0;
while (a % i == 0)
{
a /= i;
c++;
}
// If c+1 is a prime number and a = 1
if (a == 1 && Prime(c + 1))
return true;
// The number cannot have two factors
// to have count of divisors prime
else
return false;
}
// Else the number is prime so
// it has only two divisors
return true;
}
// Driver rcode
n = 13;
if (primeCountDivisors(n))
document.write("Yes");
else
document.write("No");
// This code is contributed by SoumikMondal
</script>
Time Complexity: O(sqrt(n)), as we are using a loop to traverse sqrt (n) times. Where n is the integer given as input.
Auxiliary Space: O(1), as we are not using any extra space.
Approach 2: HashMap:
- The approach uses a map to count the frequency of each prime factor. A map is a data structure in C++ that stores key-value pairs. In this case, the key is the prime factor, and the value is the frequency of that prime factor. The map is used because it allows us to keep track of the frequency of each prime factor efficiently without needing to know the prime factors beforehand.
- The approach then uses a for loop to iterate over all the prime factors and count their frequency using the map. It also checks if there is any remaining factor greater than 1 after dividing by all the prime factors up to the square root of the number. If there is such a factor, it is also included in the map with a frequency of 1.
- After counting the frequency of each prime factor, the approach uses another for loop to calculate the total number of divisors of the number using the formula (f1+1) * (f2+1) * ... * (fn+1), where f1, f2, ..., fn are the frequencies of each prime factor in the factorization of the number. This formula works because for each prime factor, we have (frequency + 1) choices for how many times to include that prime factor in a divisor. We multiply all these choices together to get the total number of divisors.
- Finally, the approach checks if the total number of divisors is a prime number using another for loop that checks if the number is divisible by any number from 2 up to the square root of the number of divisors. If it is divisible by any of these numbers, then it is not a prime number and the function returns false. If none of these numbers divide the number of divisors, then it is a prime number, and the function returns true.
Here is the code of this approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function that returns true if n
// has a prime count of divisors
bool primeCountDivisors(int n)
{
if (n < 2)
return false;
// Find all the prime factors of n
vector<int> primes;
for (int i = 2; i <= sqrt(n); i++) {
while (n % i == 0) {
primes.push_back(i);
n /= i;
}
}
if (n > 1) {
primes.push_back(n);
}
// Count the frequency of each prime factor
map<int, int> freq;
for (int prime : primes) {
freq[prime]++;
}
// Calculate the number of divisors of n
int numDivisors = 1;
for (auto it : freq) {
numDivisors *= (it.second + 1);
}
// Check if the number of divisors is a prime number or not
if (numDivisors < 2)
return false;
for (int i = 2; i <= sqrt(numDivisors); i++) {
if (numDivisors % i == 0)
return false;
}
return true;
}
// Driver code
int main()
{
int n = 13;
if (primeCountDivisors(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
public class PrimeCountDivisors {
public static boolean primeCountDivisors(int n) {
if (n < 2) {
return false;
}
// Find all the prime factors of n and their occurrences using a HashMap
Map<Integer, Integer> primes = new HashMap<>();
for (int i = 2; i <= Math.sqrt(n); i++) {
while (n % i == 0) {
// Increment the count of the prime factor in the HashMap
primes.put(i, primes.getOrDefault(i, 0) + 1);
n /= i; // Reduce n by dividing it by the prime factor
}
}
// If n is still greater than 1, it is a prime factor itself
if (n > 1) {
primes.put(n, 1);
}
// Calculate the number of divisors of n using the prime factorization
int numDivisors = 1;
for (Map.Entry<Integer, Integer> entry : primes.entrySet()) {
numDivisors *= (entry.getValue() + 1);
}
// Check if the number of divisors is a prime number or not
// If the number of divisors is less than 2, it is not prime
if (numDivisors < 2) {
return false;
}
// Check if the number of divisors is prime by checking for divisors from 2 to sqrt(numDivisors)
for (int i = 2; i <= Math.sqrt(numDivisors); i++) {
if (numDivisors % i == 0) {
return false; // If a divisor is found, numDivisors is not a prime number
}
}
// If no divisors are found other than 1 and numDivisors, it is a prime number
return true;
}
public static void main(String[] args) {
int n = 13;
// Check if the number of divisors of 'n' is a prime number
if (primeCountDivisors(n)) {
System.out.println("Yes"); // If it's prime, print "Yes"
} else {
System.out.println("No"); // If it's not prime, print "No"
}
}
}
Python3
import math
# Function that returns True if n has a prime count of divisors
def primeCountDivisors(n):
if n < 2:
return False
# Find all the prime factors of n
primes = []
i = 2
while i <= math.sqrt(n):
while n % i == 0:
primes.append(i)
n //= i
i += 1
if n > 1:
primes.append(n)
# Count the frequency of each prime factor
freq = {}
for prime in primes:
freq[prime] = freq.get(prime, 0) + 1
# Calculate the number of divisors of n
numDivisors = 1
for count in freq.values():
numDivisors *= (count + 1)
# Check if the number of divisors is a prime number or not
if numDivisors < 2:
return False
for i in range(2, int(math.sqrt(numDivisors)) + 1):
if numDivisors % i == 0:
return False
return True
# Driver code
if __name__ == "__main__":
n = 13
if primeCountDivisors(n):
print("Yes")
else:
print("No")
C#
using System;
using System.Collections.Generic;
class Program {
static bool PrimeCountDivisors(int n)
{
if (n < 2)
return false;
// Find all the prime factors of n
List<int> primes = new List<int>();
for (int i = 2; i <= Math.Sqrt(n); i++) {
while (n % i == 0) {
primes.Add(i);
n /= i;
}
}
if (n > 1) {
primes.Add(n);
}
// Count the frequency of each prime factor
Dictionary<int, int> freq
= new Dictionary<int, int>();
foreach(int prime in primes)
{
if (freq.ContainsKey(prime)) {
freq[prime]++;
}
else {
freq[prime] = 1;
}
}
// Calculate the number of divisors of n
int numDivisors = 1;
foreach(KeyValuePair<int, int> pair in freq)
{
numDivisors *= (pair.Value + 1);
}
// Check if the number of divisors is a prime number
// or not
if (numDivisors < 2)
return false;
for (int i = 2; i <= Math.Sqrt(numDivisors); i++) {
if (numDivisors % i == 0)
return false;
}
return true;
}
static void Main()
{
int n = 13;
if (PrimeCountDivisors(n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by sarojmcy2e
JavaScript
// Function that returns true if n
// has a prime count of divisors
function primeCountDivisors(n) {
if (n < 2) return false;
// Find all the prime factors of n
let primes = [];
for (let i = 2; i <= Math.sqrt(n); i++) {
while (n % i === 0) {
primes.push(i);
n /= i;
}
}
if (n > 1) {
primes.push(n);
}
// Count the frequency of each prime factor
let freq = {};
for (let prime of primes) {
freq[prime] = (freq[prime] || 0) + 1;
}
// Calculate the number of divisors of n
let numDivisors = 1;
for (let key in freq) {
numDivisors *= (freq[key] + 1);
}
// Check if the number of divisors is a prime number or not
if (numDivisors < 2) return false;
for (let i = 2; i <= Math.sqrt(numDivisors); i++) {
if (numDivisors % i === 0) return false;
}
return true;
}
// Driver code
let n = 13;
if (primeCountDivisors(n)) {
console.log("Yes");
} else {
console.log("No");
}
Output:
Yes
Time Complexity: O(sqrt(N)), as we are using a loop to traverse sqrt (N) times. Where n is the integer given as input.
Auxiliary Space: O(LogN), as we are not using any extra space.
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