The kth Factor of n Medium 0 attempts
LeetCode ↗

The kth Factor of n

Medium MatrixBFSDFS LeetCode

Given two positive integers n and k, list the factors of n in increasing order and return the k-th one. If n has fewer than k factors, return -1.

Input Format
Implement kthFactor(n, k). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

Input
n = 12
k = 3
Output
3

Example 2

Input
n = 7
k = 2
Output
7

Example 3

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

Simple Iteration

javascript
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