![]() |
VOOZH | about |
Given an integer n, count the numbers having an odd number of factors from 1 to n (inclusive).
Examples :
Input: n = 5
Output: 2
Explanation: The numbers from 1 to 5 with an odd number of factors are 1 and 4.
1 has 1 factor: [1]
4 has 3 factors: [1, 2, 4]
Hence, the count is 2.
Input: n = 1
Output: 1
Explanation: 1 has exactly one factor, [1], which is odd. Therefore, the count is 1
Table of Content
The idea is to iterate through all numbers from
1tonand count their factors by checking divisors up to their square root. If a number has an odd number of factors, increment the result. Finally, return the total count of such numbers.
2
Time Complexity: O(nān)
Auxiliary Space: O(1)
The idea is based on the observation that only perfect squares have an odd number of factors. Therefore, the required count is simply the number of perfect squares in the range
[1, n], which is equal to the integer part ofān.
Factors occur in pairs (d, n/d), so a non-perfect square has an even number of factors. A perfect square has one unpaired factor, ān, giving it an odd number of factors. Hence, only perfect squares have an odd number of factors, and the answer is āānā.
n = 5. sqrt(5), which is approximately 2.236. res = 2. 2 perfect squares (1 and 4) in the range [1, 5]. 2
Time Complexity: O(1)
Auxiliary Space: O(1)