Skip to problem
←

Kth Factor of n

Medium 0 attempts

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.

A factor is a positive divisor: an integer d for which n % d equals zero. Count each divisor once, including 1 and n. Ranking starts at 1. For n = 12, the ordered factors are [1,2,3,4,6,12], so k = 3 gives 3.

Function contract

Implement kthFactor(n, k).

Output: Return the kth positive divisor in increasing order, using 1-based ranking, or -1 if it does not exist.

Example 1

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
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)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript