class Solution:
def kthFactor(self, n: int, k: int) -> int:
count = 0
for i in range(1, n+1):
if n % i == 0:
count += 1
if count == k:
return i
return -1
class Solution {
public:
int kthFactor(int n, int k) {
int count = 0;
for (int i = 1; i <= n; ++i) {
if (n % i == 0) {
++count;
if (count == k)
return i;
}
}
return -1;
}
};
class Solution {
public int kthFactor(int n, int k) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
if (count == k)
return i;
}
}
return -1;
}
}
var kthFactor = function(n, k) {
let count = 0;
for (let i = 1; i <= n; i++) {
if (n % i === 0) {
count++;
if (count === k) return i;
}
}
return -1;
};
Given two positive integers n
and k
, you are asked to find the k
th smallest factor of n
.
A factor of n
is defined as an integer i
such that n % i == 0
(i.e., i
divides n
exactly).
Factors are considered in increasing order. If n
has fewer than k
factors, return -1
.
n
has at least k
factors.-1
if the k
th factor does not exist.
The problem asks for the k
th factor of n
in ascending order. The most straightforward way to approach this is to check every integer from 1
to n
and collect those that divide n
without a remainder. We can count these factors as we go, and when we reach the k
th one, we return it.
However, iterating through all numbers up to n
can be slow for large n
. To optimize, we can observe that factors come in pairs: if i
is a factor, then n / i
is also a factor. This allows us to only check up to the square root of n
and build the list of factors more efficiently.
The main idea is to balance simplicity (brute-force) and efficiency (using factor pairs), depending on the problem constraints.
i
in this range, check if n % i == 0
. If so, i
is a factor.
k
, return the current factor i
immediately.
k
factors, return -1
.
This approach is easy to implement and understand. For further optimization, one could collect all factors up to the square root of n
, sort them, and assemble the full list of factors in order, but for most constraints, the above method is sufficient.
Let's walk through the process with n = 12
and k = 3
:
Since we've found the 3rd factor at i = 3
, we return 3
as the answer.
If k = 6
, the process would continue:
The 6th factor is 12.
If k = 7
, we would finish the loop without finding a 7th factor, so we return -1
.
The brute-force method is simple and often fast enough for small to moderate values of n
. For very large n
, the optimized approach is preferred.
The problem asks us to find the k
th smallest factor of n
. The direct solution checks each number up to n
and counts factors until the k
th is found, which is easy to implement and understand. For larger values of n
, optimization via factor pairs can reduce the number of checks. The key insight is that factors always come in pairs, and we only need to count them in order. This makes the solution both efficient and elegant for a wide range of input sizes.