Skip to content

Commit 10c08eb

Browse files
authored
Create the-kth-factor-of-n.py
1 parent 01272f7 commit 10c08eb

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Python/the-kth-factor-of-n.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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]

0 commit comments

Comments
 (0)