VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-all-factors-of-a-natural-number/

⇱ All Factors or Divisors - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All Factors or Divisors

Last Updated : 2 Apr, 2026

Given a positive integer n, find all the distinct divisors of n.

Examples:

Input: n = 10
Output: [1, 2, 5, 10]
Explanation: 1, 2, 5 and 10 are the divisors of 10.

Input: n = 100
Output: [1, 2, 4, 5, 10, 20, 25, 50, 100]
Explanation: 1, 2, 4, 5, 10, 20, 25, 50 and 100 are divisors of 100.

[Naive Approach] Iterating till n - O(n) Time and O(1) Space

The idea is to iterate over all the numbers from 1 to n and for each number check if the number divides n. If the number divides n, print it.


Output
1 2 5 10 

[Expected Approach] Finding all factors in pairs - O(sqrt(n)) Time and O(1) Space

If we look carefully, all the divisors of a number appear in pairs.
For example, if n = 100, then the divisor pairs are:
(1, 100), (2, 50), (4, 25), (5, 20), (10, 10).

We need to be careful in cases like (10, 10)—i.e., when both divisors in a pair are equal (which happens when n is a perfect square). In such cases, we should include that divisor only once.
Using this fact, we can optimize our program significantly.

Instead of iterating from 1 to n, we only need to iterate from 1 to √n.
Why? Because for any factor a of n, the corresponding factor b = n / a forms a pair (a, b).
At least one of the two values in any such pair must lie within the range [1, √n].

So, we can:

  • Iterate from 1 to √n to find all divisors less than or equal to √n.
  • For each such divisor d, also add n / d as the paired divisor.
  • Take care not to duplicate the square root divisor if n is a perfect square.
👁 Factors-occurring-in-pairs

Output
1 10 2 5 
Comment