Given two numbers n and k, print k-th prime factor among all prime factors of n. For example, if the input number is 15 and k is 2, then output should be “5”. And if the k is 3, then output should be “-1” (there are less than k prime factors).
Input : n = 225, k = 2 Output : 3 Prime factors are 3 3 5 5. Second prime factor is 3. Input : n = 81, k = 5 Output : -1 Prime factors are 3 3 3 3
A Simple Solution is to first find prime factors of n. While finding prime factors, keep track of count. If count becomes k, we return current prime factor.
An Efficient Solution is to use Sieve of Eratosthenes. Note that this solution is efficient when we need k-th prime factor for multiple test cases. For a single case, previous approach is better.
The idea is to do preprocessing and store least prime factor of all numbers in given range. Once we have least prime factors stored in an array, we can find k-th prime factor by repeatedly dividing n with least prime factor while it is divisible, then repeating the process for reduced n.
This article is contributed by Afzal Ansari. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- N-th prime factor of a given number
- Sum of largest prime factor of each number less than equal to n
- Find largest prime factor of a number
- Find sum of a number and its maximum prime factor
- Prime Factor
- Least prime factor of numbers till n
- Exactly n distinct prime factor numbers from a to b
- Queries on the sum of prime factor counts in a range
- Count all the numbers less than 10^6 whose minimum prime factor is N
- Nearest element with at-least one common prime factor
- Count of subarrays whose products don't have any repeating prime factor
- Numbers with sum of digits equal to the sum of digits of its all prime factor
- Factor Tree of a given Number
- Smallest number S such that N is a factor of S factorial or S!
- Largest factor of a given number which is a perfect square
Improved By : nitin mittal