The kth Factor of n Medium 0 attempts
LeetCode ↗

The kth Factor of n

Medium MatrixBFSDFS LeetCode

Given two positive integers n and k, return the kth factor of n, or -1 if n has fewer than k factors.

Example: n = 12, k = 3 → Output: 3 (factors: 1,2,3,4,6,12)

Sample Input
Sample Output
Constraints
  • 1 <= k <= n <= 1000
Test Cases
Case 1
Args: [12,3] Expected: 3
Case 2
Args: [7,2] Expected: 7
Case 3
Args: [4,4] Expected: -1
Topics

Simple Iteration

function kthFactor(n, k) {
  for (let i = 1; i <= n; i++) {
    if (n % i === 0 && --k === 0) return i;
  }
  return -1;
}

Time: O(n) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript