VOOZH about

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

⇱ All Factors in Sorted Order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All Factors in Sorted Order

Last Updated : 5 Apr, 2026

Given a natural number n, print all distinct divisors in sorted order.

Examples:

Input : n = 10
Output: 1 2 5 10

Input: n = 100
Output: 1 2 4 5 10 20 25 50 100

Input: n = 125
Output: 1 5 25 125

We have discussed how to find all the divisors of a number here:All Factors or Divisors

Using Two Arrays - O(√n) Time and O(√n) Space

  • Check factors up to √n because factors come in pairs: n = a × b. When a is small (≤ √n), its pair b = n / a is large (≥ √n). So by iterating i from 1 to √n, we find one of the two factors as i and n/i.
  • When we iterate through factors, the smallest factor i gives the largest pair (n/i) as smaller value of i means larger value (n/i).
  • Storing smaller factors first and then adding larger factors in reverse gives all divisors in sorted order without sorting.
  • We need to handle perfect squares explicitly as we need to print all divisors only once.

Output
1 2 4 5 10 20 25 50 100 

Constant Extra Space - O(√n) Time and O(1) Space

This is mainly a space optimization over the above approach. We first get the smaller factor of pairs in sorted order traversing i to √n. To get the larger factors in increasing order, we traverse back from i - 1 (which is around √n - 1) to 1 and instead of storing i, we store n/i so that we larger elements of pairs in increasing order.

For example, let n = 10.

Step 1: Loop from 1 → √n (√10 ≈ 3, so check only 1, 2, 3)

  • i = 1 ->10 % 1 == 0 -> print 1
  • i = 2 -> 10 % 2 == 0 -> print 2
  • i = 3 -> not divisible -> ignore

Step 2: i = i - 1, i = 2

Step 2: Traverse from 2 to 1

  • i = 2 -> 10 / 2 = 5 -> print 5
  • i = 1 -> 10 / 1 = 10 -> print 10

Final Output : 1, 2, 5, 10


Output
1 2 4 5 10 20 25 50 100 
Comment
Article Tags: