forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-kth-factor-of-n.cpp
51 lines (48 loc) · 1.16 KB
/
the-kth-factor-of-n.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Time: O(sqrt(n))
// Space: O(1)
class Solution {
public:
int kthFactor(int n, int k) {
const auto& [mid, count] = kthFactor_(n);
int total = 2 * count - (mid * mid == n);
if (k > total) {
return -1;
}
int result = kthFactor_(n, (k <= count) ? k : total - (k - 1)).first;
return (k <= count) ? result : n / result;
}
private:
pair<int, int> kthFactor_(int n, int k = 0) {
int mid = -1;
for (int i = 1; i * i <= n; ++i) {
if (n % i) {
continue;
}
mid = i;
if (!--k) {
break;
}
}
return {mid, -k};
}
};
// Time: O(sqrt(n))
// Space: O(sqrt(n))
class Solution2 {
public:
int kthFactor(int n, int k) {
vector<int> result;
for (int i = 1; i * i <= n; ++i) {
if (n % i) {
continue;
}
if (i * i != n) {
result.emplace_back(i);
}
if (!--k) {
return i;
}
}
return (k > result.size()) ? -1 : n / result[result.size() - k];
}
};