forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperfect_cube.py
47 lines (40 loc) · 1.04 KB
/
perfect_cube.py
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
def perfect_cube(n: int) -> bool:
"""
Check if a number is a perfect cube or not.
>>> perfect_cube(27)
True
>>> perfect_cube(4)
False
"""
val = n ** (1 / 3)
return (val * val * val) == n
def perfect_cube_binary_search(n: int) -> bool:
"""
Check if a number is a perfect cube or not using binary search.
Time complexity : O(Log(n))
Space complexity: O(1)
>>> perfect_cube_binary_search(27)
True
>>> perfect_cube_binary_search(64)
True
>>> perfect_cube_binary_search(4)
False
>>> perfect_cube_binary_search("a")
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'str'
"""
left = 0
right = n
while left <= right:
mid = left + (right - left) // 2
if mid * mid * mid == n:
return True
elif mid * mid * mid < n:
left = mid + 1
else:
right = mid - 1
return False
if __name__ == "__main__":
import doctest
doctest.testmod()