![]() |
VOOZH | about |
Given an integer N, the task is to find the number of factors of N which are a perfect square.
Examples:
Input: N = 100
Output: 4
Explanation:
There are four factors of
100 (1, 4, 25, 100) that are perfect square.
Input: N = 900
Output: 8
Explanation:
There are eight factors of 900 (1, 4, 9, 25, 36, 100, 225, 900) that are perfect square.
Naive Approach: The simplest approach to solve this problem is to find all possible factors of the given number Nand for each factor, check if the factor is a perfect square or not. For every factor found to be so, increase count. Print the final count.
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach:
The following observations need to be made to optimize the above approach:
The number of factors for a number is given by:
Factors of N = (1 + a1)*(1 + a2)*(1 + a3)*..*(1 + an)
where a1, a2, a3, ..., an are the count of distinct prime factors of N.
In a perfect square, the count of distinct prime factors must be divisible by 2. Therefore, the count of factors that are a perfect square is given by:
Factors of N that are perfect square = (1 + a1/2)*(1 + a2/2)*...*(1 + an/2) where a1, a2, a3, …, an are the count of distinct prime factors of N.
Illustration:
The prime factors of N = 100 are 2, 2, 5, 5.
Therefore, the number of factors that are perfect square are (1 + 2/2) * (1 + 2/2) = 4.
The factors are 1, 4, 25, 100.
Therefore, find the count of prime factors and apply the above formula to find the count of factors that are a perfect square.
Below is the implementation of the above approach:
4
Time Complexity:
Space Complexity: O(1)
In this approach, we will iterate through all the factors of the given number and check if each factor is a perfect square or not. If a factor is a perfect square, we will increment the count.
4 8
Time complexity: O(N)
Space complexity: O(1)