VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-elements-odd-factors-given-range/

⇱ Numbers with Odd Factors in Given Range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Numbers with Odd Factors in Given Range

Last Updated : 7 Jun, 2026

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

[Naive Approach] Check Factors for Every Number - O(n√n) Time O(1) Space

The idea is to iterate through all numbers from 1 to n and 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.


Output
2

Time Complexity: O(n√n)
Auxiliary Space: O(1)

[Expected Approach] Count Perfect Squares - O(1) Time O(1) Space

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āŒ‹.

  • Initialize n = 5.
  • Compute sqrt(5), which is approximately 2.236.
  • Convert it to an integer: res = 2.
  • This means there are 2 perfect squares (1 and 4) in the range [1, 5].

Output
2

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: