The kth Factor of n - Problem

You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.

Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.

Input & Output

Example 1 — Basic Case
$ Input: n = 12, k = 3
Output: 3
💡 Note: Factors of 12 in ascending order: [1, 2, 3, 4, 6, 12]. The 3rd factor is 3.
Example 2 — Not Enough Factors
$ Input: n = 7, k = 2
Output: 7
💡 Note: Factors of 7 are [1, 7]. The 2nd factor is 7.
Example 3 — Perfect Square
$ Input: n = 4, k = 4
Output: -1
💡 Note: Factors of 4 are [1, 2, 4]. There are only 3 factors, so the 4th factor doesn't exist.

Constraints

  • 1 ≤ k ≤ n ≤ 1000

Visualization

Tap to expand
The kth Factor of n - Square Root Approach INPUT n = 12 Find factors of 12 k = 3 Return 3rd factor All Factors of 12: 1 2 3 4 6 12 1st 2nd 3rd 4th 5th 6th sqrt(12) = 3.46 Check i from 1 to 3 ALGORITHM STEPS 1 Loop i: 1 to sqrt(n) For i=1,2,3 check if n % i == 0 2 Count small factors i=1: 12%1=0 [OK] k=2 i=2: 12%2=0 [OK] k=1 i=3: 12%3=0 [OK] k=0 3 Found at i=3! k becomes 0, return i Answer = 3 4 Handle large factors (Not needed here) n/i gives: 12,6,4 Factor Pairs i n/i k 1 12 2 2 6 1 3 4 0 FINAL RESULT Output: 3 The 3rd factor of 12 is 3 [OK] Answer found! Complexity Analysis Time: O(sqrt(n)) Space: O(1) Why sqrt(n)? Factors come in pairs: (1,12) (2,6) (3,4) Key Insight: Instead of checking all numbers from 1 to n, we only check up to sqrt(n). For each factor i found, n/i is also a factor. We first count small factors (i), then large factors (n/i) in reverse order. This reduces time complexity from O(n) to O(sqrt(n)). TutorialsPoint - The kth Factor of n | Square Root Approach
Asked in
Facebook 15 Amazon 12
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen