Given a natural number n, print all distinct divisors of it.
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 strongly recommend to refer below article as a prerequisite.
Find all divisors of a natural number | Set 1
In the above post, we had found a way to find all the divisors in O(sqrt(n)) .
However there is still a minor problem in the solution, can you guess?
Yes! the output is not in a sorted fashion which we had got using brute-force technique.
How to print the output in sorted order?
If we observe the output which we had got, we can analyze that the divisors are printed in a zig-zag fashion (small, large pairs). Hence if we store half of them then we can print then in a sorted order.
Below is a implementation for the same:
The divisors of 100 are: 1 2 4 5 10 20 25 50 100
Time Complexity : O(sqrt(n))
Auxiliary Space : O(sqrt(n))
This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find sum of divisors of all the divisors of a natural number
- Find all divisors of a natural number | Set 1
- Sum of all proper divisors of a natural number
- Find sum of inverse of the divisors when sum of divisors and the number is given
- Find the sum of the number of divisors
- Find number from its divisors
- Sum of all proper divisors of natural numbers in an array
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors
- Find the largest good number in the divisors of given number N
- Find the number of divisors of all numbers in the range [1, n]
- Program to find count of numbers having odd number of divisors in given range
- Find if given number is sum of first n natural numbers
- Find sum of modulo K of first N natural number
- Find the first natural number whose factorial is divisible by x
- Find the k-th smallest divisor of a natural number N