forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosest-divisors.py
More file actions
35 lines (30 loc) · 843 Bytes
/
closest-divisors.py
File metadata and controls
35 lines (30 loc) · 843 Bytes
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
# Time: O(sqrt(n))
# Space: O(1)
class Solution(object):
def closestDivisors(self, num):
"""
:type num: int
:rtype: List[int]
"""
def divisors(n):
for d in reversed(xrange(1, int(n**0.5)+1)):
if n % d == 0:
return d, n//d
return 1, n
return min([divisors(num+1), divisors(num+2)], key=lambda x: x[1]-x[0])
# Time: O(sqrt(n))
# Space: O(1)
class Solution2(object):
def closestDivisors(self, num):
"""
:type num: int
:rtype: List[int]
"""
result, d = [1, num+1], 1
while d*d <= num+2:
if (num+2) % d == 0:
result = [d, (num+2)//d]
if (num+1) % d == 0:
result = [d, (num+1)//d]
d += 1
return result