Count all perfect divisors of a number
Last Updated :
23 Jul, 2025
Given a number n, count total perfect divisors of n. Perfect divisors are those divisors which are square of some integer. For example a perfect divisor of 8 is 4.
Examples:
Input : n = 16
Output : 3
Explanation : There are only 5 divisor of 16:
1, 2, 4, 8, 16. Only three of them are perfect
squares: 1, 4, 16. Therefore the answer is 3
Input : n = 7
Output : 1
Naive approach
A brute force is find all the divisors of a number. Count all divisors that are perfect squares.
C++
// Below is C++ code to count total perfect Divisors
#include<bits/stdc++.h>
using namespace std;
// Utility function to check perfect square number
bool isPerfectSquare(int n)
{
int sq = (int) sqrt(n);
return (n == sq * sq);
}
// Returns count all perfect divisors of n
int countPerfectDivisors(int n)
{
// Initialize result
int count = 0;
// Consider every number that can be a divisor
// of n
for (int i=1; i*i <= n; ++i)
{
// If i is a divisor
if (n%i == 0)
{
if (isPerfectSquare(i))
++count;
if (n/i != i && isPerfectSquare(n/i))
++count;
}
}
return count;
}
// Driver code
int main()
{
int n = 16;
cout << "Total perfect divisors of "
<< n << " = " << countPerfectDivisors(n) << "\n";
n = 12;
cout << "Total perfect divisors of "
<< n << " = " << countPerfectDivisors(n);
return 0;
}
Java
// Java code to count
// total perfect Divisors
import java.io.*;
class GFG
{
// Utility function to check
// perfect square number
static boolean isPerfectSquare(int n)
{
int sq = (int) Math.sqrt(n);
return (n == sq * sq);
}
// Returns count all
// perfect divisors of n
static int countPerfectDivisors(int n)
{
// Initialize result
int count = 0;
// Consider every number
// that can be a divisor of n
for (int i = 1; i * i <= n; ++i)
{
// If i is a divisor
if (n % i == 0)
{
if (isPerfectSquare(i))
++count;
if (n / i != i &&
isPerfectSquare(n / i))
++count;
}
}
return count;
}
// Driver code
public static void main (String[] args)
{
int n = 16;
System.out.print("Total perfect " +
"divisors of " + n);
System.out.println(" = " +
countPerfectDivisors(n));
n = 12;
System.out.print("Total perfect " +
"divisors of " + n);
System.out.println(" = " +
countPerfectDivisors(n));
}
}
// This code is contributed by ajit
Python3
# Python3 implementation of Naive method
# to count all perfect divisors
import math
def isPerfectSquare(x) :
sq = (int)(math.sqrt(x))
return (x == sq * sq)
# function to count all perfect divisors
def countPerfectDivisors(n) :
# Initialize result
cnt = 0
# Consider every number that
# can be a divisor of n
for i in range(1, (int)(math.sqrt(n)) + 1) :
# If i is a divisor
if ( n % i == 0 ) :
if isPerfectSquare(i):
cnt = cnt + 1
if n/i != i and isPerfectSquare(n/i):
cnt = cnt + 1
return cnt
# Driver program to test above function
print("Total perfect divisor of 16 = ",
countPerfectDivisors(16))
print("Total perfect divisor of 12 = ",
countPerfectDivisors(12))
# This code is contributed by Saloni Gupta
C#
// C# code to count
// total perfect Divisors
using System;
class GFG
{
// Utility function to check
// perfect square number
static bool isPerfectSquare(int n)
{
int sq = (int) Math.Sqrt(n);
return (n == sq * sq);
}
// Returns count all
// perfect divisors of n
static int countPerfectDivisors(int n)
{
// Initialize result
int count = 0;
// Consider every number
// that can be a divisor of n
for (int i = 1;
i * i <= n; ++i)
{
// If i is a divisor
if (n % i == 0)
{
if (isPerfectSquare(i))
++count;
if (n / i != i &&
isPerfectSquare(n / i))
++count;
}
}
return count;
}
// Driver code
static public void Main ()
{
int n = 16;
Console.Write("Total perfect " +
"divisors of " + n);
Console.WriteLine(" = " +
countPerfectDivisors(n));
n = 12;
Console.Write("Total perfect " +
"divisors of " + n);
Console.WriteLine(" = " +
countPerfectDivisors(n));
}
}
// This code is contributed
// by akt_mit
PHP
<?php
// PHP code to count
// total perfect Divisors
// function to check
// perfect square number
function isPerfectSquare($n)
{
$sq = sqrt($n);
return ($n == $sq * $sq);
}
// Returns count all
// perfect divisors of n
function countPerfectDivisors($n)
{
// Initialize result
$count = 0;
// Consider every number
// that can be a divisor
// of n
for ($i = 1; $i * $i <= $n; ++$i)
{
// If i is a divisor
if ($n % $i == 0)
{
if (isPerfectSquare($i))
++$count;
if ($n / $i != $i &&
isPerfectSquare($n / $i))
++$count;
}
}
return $count;
}
// Driver Code
$n = 16;
echo "Total perfect divisors of ",
$n, " = ", countPerfectDivisors($n), "\n";
$n = 12;
echo "Total perfect divisors of ",
$n, " = ", countPerfectDivisors($n);
// This code is contributed by ajit
?>
JavaScript
<script>
// JavaScript program for the above approach
// Utility function to check
// perfect square number
function isPerfectSquare(n)
{
let sq = Math.sqrt(n);
return (n == sq * sq);
}
// Returns count all
// perfect divisors of n
function countPerfectDivisors(n)
{
// Initialize result
let count = 0;
// Consider every number
// that can be a divisor of n
for (let i = 1; i * i <= n; ++i)
{
// If i is a divisor
if (n % i == 0)
{
if (isPerfectSquare(i))
++count;
if (n / i != i &&
isPerfectSquare(n / i))
++count;
}
}
return count;
}
// Driver Code
let n = 16;
document.write("Total perfect " +
"divisors of " + n);
document.write(" = " +
countPerfectDivisors(n) + "<br/>");
n = 12;
document.write("Total perfect " +
"divisors of " + n);
document.write(" = " +
countPerfectDivisors(n));
// This code is contributed by chinmoy1997pal.
</script>
Output:
Total Perfect divisors of 16 = 3
Total Perfect divisors of 12 = 2
Time complexity: O(sqrt(n))
Auxiliary space: O(1)
Efficient approach (For large number of queries)
The idea is based on Sieve of Eratosthenes. This approach is beneficial if there are large number of queries. Following is the algorithm to find all perfect divisors up to n numbers.
- Create a list of n consecutive integers from 1 to n:(1, 2, 3, ..., n)
- Initially, let d be 2, the first divisor
- Starting from 4(square of 2) increment all the multiples of 4 by 1 in perfectDiv[] array, as all these multiples contain 4 as perfect divisor. These numbers will be 4d, 8d, 12d, ... etc
- Repeat the 3rd step for all other numbers. The final array of perfectDiv[] will contain all the count of perfect divisors from 1 to n
Below is implementation of above steps.
C++
// Below is C++ code to count total perfect
// divisors
#include<bits/stdc++.h>
using namespace std;
#define MAX 100001
int perfectDiv[MAX];
// Pre-compute counts of all perfect divisors
// of all numbers upto MAX.
void precomputeCounts()
{
for (int i=1; i*i < MAX; ++i)
{
// Iterate through all the multiples of i*i
for (int j=i*i; j < MAX; j += i*i)
// Increment all such multiples by 1
++perfectDiv[j];
}
}
// Returns count of perfect divisors of n.
int countPerfectDivisors(int n)
{
return perfectDiv[n];
}
// Driver code
int main()
{
precomputeCounts();
int n = 16;
cout << "Total perfect divisors of "
<< n << " = " << countPerfectDivisors(n) << "\n";
n = 12;
cout << "Total perfect divisors of "
<< n << " = " << countPerfectDivisors(n);
return 0;
}
Java
// Java code to count total perfect
// divisors
class GFG
{
static int MAX = 100001;
static int[] perfectDiv = new int[MAX];
// Pre-compute counts of all perfect divisors
// of all numbers upto MAX.
static void precomputeCounts()
{
for (int i = 1; i * i < MAX; ++i)
{
// Iterate through all the multiples of i*i
for (int j = i * i; j < MAX; j += i * i)
// Increment all such multiples by 1
++perfectDiv[j];
}
}
// Returns count of perfect divisors of n.
static int countPerfectDivisors(int n)
{
return perfectDiv[n];
}
// Driver code
public static void main (String[] args)
{
precomputeCounts();
int n = 16;
System.out.println("Total perfect divisors of " +
n + " = " + countPerfectDivisors(n));
n = 12;
System.out.println("Total perfect divisors of " +
n + " = " + countPerfectDivisors(n));
}
}
// This code is contributed by mits
Python3
# Below is Python3 code to count total perfect
# divisors
MAX = 100001
perfectDiv= [0]*MAX
# Pre-compute counts of all perfect divisors
# of all numbers upto MAX.
def precomputeCounts():
i=1
while i*i < MAX:
# Iterate through all the multiples of i*i
for j in range(i*i,MAX,i*i):
# Increment all such multiples by 1
perfectDiv[j] += 1
i += 1
# Returns count of perfect divisors of n.
def countPerfectDivisors( n):
return perfectDiv[n]
# Driver code
if __name__ == "__main__":
precomputeCounts()
n = 16
print ("Total perfect divisors of "
, n , " = " ,countPerfectDivisors(n))
n = 12
print ( "Total perfect divisors of "
,n ," = " ,countPerfectDivisors(n))
C#
// C# code to count total perfect
// divisors
using System;
class GFG
{
static int MAX = 100001;
static int[] perfectDiv = new int[MAX];
// Pre-compute counts of all perfect
// divisors of all numbers upto MAX.
static void precomputeCounts()
{
for (int i = 1; i * i < MAX; ++i)
{
// Iterate through all the multiples of i*i
for (int j = i * i; j < MAX; j += i * i)
// Increment all such multiples by 1
++perfectDiv[j];
}
}
// Returns count of perfect divisors of n.
static int countPerfectDivisors(int n)
{
return perfectDiv[n];
}
// Driver code
public static void Main()
{
precomputeCounts();
int n = 16;
Console.WriteLine("Total perfect divisors of " + n +
" = " + countPerfectDivisors(n));
n = 12;
Console.WriteLine("Total perfect divisors of " + n +
" = " + countPerfectDivisors(n));
}
}
// This code is contributed by mits
PHP
<?php
// Below is PHP code to count total
// perfect divisors
$MAX = 10001;
$perfectDiv = array_fill(0, $MAX, 0);
// Pre-compute counts of all perfect
// divisors of all numbers upto MAX.
function precomputeCounts()
{
global $MAX, $perfectDiv;
for ($i = 1; $i * $i < $MAX; ++$i)
{
// Iterate through all the multiples
// of i*i
for ($j = $i * $i;
$j < $MAX; $j += $i * $i)
// Increment all such multiples by 1
++$perfectDiv[$j];
}
}
// Returns count of perfect divisors of n.
function countPerfectDivisors($n)
{
global $perfectDiv;
return $perfectDiv[$n];
}
// Driver code
precomputeCounts();
$n = 16;
echo "Total perfect divisors of " . $n .
" = " . countPerfectDivisors($n) . "\n";
$n = 12;
echo "Total perfect divisors of " . $n .
" = " . countPerfectDivisors($n);
// This code is contributed by mits
?>
JavaScript
<script>
// Javascript code to count total perfect
// divisors
let MAX = 100001;;
let perfectDiv = new Array(MAX);
for(let i = 0; i < MAX; i++)
{
perfectDiv[i] = 0;
}
// Pre-compute counts of all perfect divisors
// of all numbers upto MAX.
function precomputeCounts()
{
for(let i = 1; i * i < MAX; ++i)
{
// Iterate through all the multiples of i*i
for(let j = i * i; j < MAX; j += i * i)
// Increment all such multiples by 1
++perfectDiv[j];
}
}
// Returns count of perfect divisors of n.
function countPerfectDivisors(n)
{
return perfectDiv[n];
}
// Driver code
precomputeCounts();
let n = 16;
document.write("Total perfect divisors of " +
n + " = " +
countPerfectDivisors(n) + "<br>");
n = 12;
document.write("Total perfect divisors of " +
n + " = " +
countPerfectDivisors(n));
// This code is contributed by rag2127
</script>
Output:
Total Perfect divisors of 16 = 3
Total Perfect divisors of 12 = 2
Time complexity: O(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