Skip to content

Commit a9cee1d

Browse files
Add perfect cube binary search (TheAlgorithms#10477)
* Add perfect cube binary search algorithm * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add support for testing negative perfect cubes * Add TypeError check for invalid inputs * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent abc3909 commit a9cee1d

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

maths/perfect_cube.py

+41-2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,45 @@ def perfect_cube(n: int) -> bool:
1111
return (val * val * val) == n
1212

1313

14+
def perfect_cube_binary_search(n: int) -> bool:
15+
"""
16+
Check if a number is a perfect cube or not using binary search.
17+
Time complexity : O(Log(n))
18+
Space complexity: O(1)
19+
20+
>>> perfect_cube_binary_search(27)
21+
True
22+
>>> perfect_cube_binary_search(64)
23+
True
24+
>>> perfect_cube_binary_search(4)
25+
False
26+
>>> perfect_cube_binary_search("a")
27+
Traceback (most recent call last):
28+
...
29+
TypeError: perfect_cube_binary_search() only accepts integers
30+
>>> perfect_cube_binary_search(0.1)
31+
Traceback (most recent call last):
32+
...
33+
TypeError: perfect_cube_binary_search() only accepts integers
34+
"""
35+
if not isinstance(n, int):
36+
raise TypeError("perfect_cube_binary_search() only accepts integers")
37+
if n < 0:
38+
n = -n
39+
left = 0
40+
right = n
41+
while left <= right:
42+
mid = left + (right - left) // 2
43+
if mid * mid * mid == n:
44+
return True
45+
elif mid * mid * mid < n:
46+
left = mid + 1
47+
else:
48+
right = mid - 1
49+
return False
50+
51+
1452
if __name__ == "__main__":
15-
print(perfect_cube(27))
16-
print(perfect_cube(4))
53+
import doctest
54+
55+
doctest.testmod()

0 commit comments

Comments
 (0)