![]() |
VOOZH | about |
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
Table of Content
1 2 4 5 10 20 25 50 100
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
1 2 4 5 10 20 25 50 100