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 email@example.com. 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.
- Find sum of even factors of a number
- Number Theory (Interesting Facts and Algorithms)
- Interesting facts about Fibonacci numbers
- Print prime numbers in a given range using C++ STL
- Find politeness of a number
- Prime Factorization using Sieve O(log n) for multiple queries
- Partition a number into two divisble parts
- Find the highest occurring digit in prime numbers in a range
- Smith Number
- Find all divisors of a natural number | Set 1
- Pollard's Rho Algorithm for Prime Factorization
- How to check if a given number is Fibonacci number?
- Efficient program to print all prime factors of a given number
- Sieve of Eratosthenes
- Program for Fibonacci numbers
Improved By : nitin mittal