VOOZH about

URL: https://www.geeksforgeeks.org/dsa/k-th-prime-factor-given-number/

⇱ k-th prime factor of a given number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

k-th prime factor of a given number

Last Updated : 9 Jun, 2026

Given two numbers n and k, find the kth prime factor of n.
Prime factors are considered with repetition and are taken in non-decreasing order. If k is greater than the total number of prime factors of n, return -1.

Examples:

Input: n = 225, k = 2
Output: 3
Explanation: The prime factorization of 225 is 3 × 3 × 5 × 5. The prime factors in non-decreasing order are [3, 3, 5, 5]. The 2nd prime factor is 3.

Input: n = 81, k = 5
Output: -1
Explanation: The prime factorization of 81 is 3 × 3 × 3 × 3. The prime factors in non-decreasing order are [3, 3, 3, 3]. There is no 5th prime factor, so return -1.

Using Trial Division - O(√n) Time and O(1) Space

The idea is to divide n by every number starting from 2 up to √n. For each divisor that divides n, we keep dividing and decrementing k for every occurrence. Since we start from the smallest divisor and move upward, prime factors are naturally extracted in non-decreasing order. If k reaches 0 during this process we return that factor. After the loop, if n is still greater than 1 then n itself is a prime factor - we check if it is the kth one. If k is still not 0 after full factorization, we return -1.


Output
3
Comment