You’re given a number N and a number K. Our task is to find the kth smallest divisor of N.
Input : N = 12, K = 5 Output : 6 The divisors of 12 after sorting are 1, 2, 3, 4, 6 and 12. Where the value of 5th divisor is equal to 6. Input : N = 16, K 2 Output : 2
Simple Approach: A simple approach is to run a loop from 1 to √N and find all factors of N and push them into a vector. Finally, sort the vector and print the K-th value from the vector.
Note: Elements in the vector will not be sorted initially as we are pushing both factors (i) and (n/i). That is why it is needed to sort the vector before printing the K-th factor.
Below is the implementation of above approach :
Time Complexity: √N log( √N )
Efficient Approach: An efficient approach will be to store the factors in two separate vectors. That is, factors i will be stored in a separate vector and N/i will be stored in a separate vector for all i from 1 to √N.
Now, if observed carefully, it can be seen that the first vector is already sorted in increasing order and the second vector is sorted in decreasing order. So, reverse the second vector and print the K-th element from either of the vectors in which it is lying.
Below is the implementation of the above approach:
Time Complexity: √N
- Greatest divisor which divides all natural number in range [L, R]
- Smallest prime divisor of a number
- Smallest number to multiply to convert floating point to natural
- Smallest divisor D of N such that gcd(D, M) is greater than 1
- Find sum of modulo K of first N natural number
- Find all divisors of a natural number | Set 1
- Find if given number is sum of first n natural numbers
- Find all divisors of a natural number | Set 2
- Find the first natural number whose factorial is divisible by x
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M
- Find smallest possible Number from a given large Number with same count of digits
- Minimum divisor of a number to make the number perfect cube
- Find the smallest number whose digits multiply to a given number n
- Find smallest number K such that K % p = 0 and q % K = 0
- Find an integer X which is divisor of all except exactly one element in an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.