Given a positive integer ‘n’ and query ‘q’. Print all the divisors of number ‘n’.
Input: 6 Output: 1 2 3 6 Explanation Divisors of 6 are: 1, 2, 3, 6 Input: 10 Output: 1 2 5 10
Naive approach is to iterate through 1 to sqrt(n) for every query ‘q’ and print the divisors accordingly. See this to understand more. Time complexity of this approach is q*sqrt(n) which is not sufficient for large number of queries.
Efficient approach is to use factorization by using sieve base approach.
- Create a list of consecutive integers from 1 to ‘n’.
- For any number ‘d’, iterate through all the multiples of ‘d’ i.e., d, 2d, 3d, … etc. Meanwhile push the divisor ‘d’ for every multiples.
Output Divisors of 10 = 1 2 5 10 Divisors of 30 = 1 2 3 5 6 10 15 303
Time complexity: O(len) for each query, where len is equal to total divisors of number ‘n’.
Auxiliary space: O(MAX)
- Find sum of divisors of all the divisors of a natural number
- Find sum of inverse of the divisors when sum of divisors and the number is given
- Check if a number is divisible by all prime divisors of another number
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors
- Querying maximum number of divisors that a number in a given range has
- Find the largest good number in the divisors of given number N
- First triangular number whose number of divisors exceeds N
- Queries on sum of odd number digit sums of all the factors of a number
- Sum of divisors of factorial of a number
- Find the sum of the number of divisors
- Sum of all the prime divisors of a number
- Find number from its divisors
- Sum of all proper divisors of a natural number
- Number of divisors of product of N numbers
- Sum of multiplication of triplet of divisors of a number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.