![]() |
VOOZH | about |
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.
Table of Content
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.
1 2 5 10
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:
1 10 2 5