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:
-1
💡 Note:
Factors of 7 are [1, 7]. Since k = 2 and there are only 2 factors, but we need the 2nd factor, answer is 7. Wait, let me recalculate: 7 has factors [1, 7], so 2nd factor is 7, not -1.
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
Understanding the Visualization
1
Input
Given n=12 and k=3
2
Process
Find all factors and sort them
3
Output
Return the 3rd factor
Key Takeaway
🎯 Key Insight: Factors come in pairs, so checking up to √n is sufficient to find all factors efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code