forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain4.cpp
42 lines (31 loc) · 764 Bytes
/
main4.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
/// Source : https://leetcode.com/problems/the-kth-factor-of-n/
/// Author : liuyubobobo
/// Time : 2020-06-27
#include <iostream>
#include <vector>
using namespace std;
/// Just calculate all the factors once
/// Time Complexity: O(sqrt(n))
/// Space Complexity: O(1)
class Solution {
public:
int kthFactor(int n, int k) {
int i;
for(i = 1; i * i <= n; i ++)
if(n % i == 0){
k --;
if(!k) return i;
}
i--;
for(i = (i * i == n ? i - 1 : i); i > 0; i --)
if(n % i == 0){
k --;
if(!k) return n / i;
}
return -1;
}
};
int main() {
cout << Solution().kthFactor(4, 4) << endl;
return 0;
}