[LeetCode] The kth Factor of n

1492. The kth Factor of n

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int kthFactor(int n, int k) {
vector<int> factors;
for(int i = 1; i * i <= n && factors.size() <= k; i++) {
if(!(n % i)) factors.push_back(i);
}

return factors.empty() ? -1 :
factors.size() >= k ? factors[k - 1] :
factors.back() * factors.back() == n ? (factors.size() << 1) - 1 >= k ? n / factors[(factors.size() << 1) - k - 1] : -1 :
(factors.size() << 1) >= k ? n / factors[(factors.size() << 1) - k] : -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/13/PS/LeetCode/the-kth-factor-of-n/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.