File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(sqrt(n))
2
+ # Space: O(1)
3
+
4
+ class Solution (object ):
5
+ def kthFactor (self , n , k ):
6
+ """
7
+ :type n: int
8
+ :type k: int
9
+ :rtype: int
10
+ """
11
+ def kth_factor (n , k = 0 ):
12
+ mid = None
13
+ i = 1
14
+ while i * i <= n :
15
+ if not n % i :
16
+ mid = i
17
+ k -= 1
18
+ if not k :
19
+ break
20
+ i += 1
21
+ return mid , - k
22
+
23
+ mid , count = kth_factor (n )
24
+ total = 2 * count - (mid * mid == n )
25
+ if k > total :
26
+ return - 1
27
+ result = kth_factor (n , k if k <= count else total - (k - 1 ))[0 ]
28
+ return result if k <= count else n // result
29
+
30
+
31
+ # Time: O(sqrt(n))
32
+ # Space: O(sqrt(n))
33
+ class Solution2 (object ):
34
+ def kthFactor (self , n , k ):
35
+ """
36
+ :type n: int
37
+ :type k: int
38
+ :rtype: int
39
+ """
40
+ result = []
41
+ i = 1
42
+ while i * i <= n :
43
+ if not n % i :
44
+ if i * i != n :
45
+ result .append (i )
46
+ k -= 1
47
+ if not k :
48
+ return i
49
+ i += 1
50
+ return - 1 if k > len (result ) else n // result [- k ]
You can’t perform that action at this time.
0 commit comments