Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions maths/perfect_cube.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,39 @@ def perfect_cube(n: int) -> bool:
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'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add your own TypeError check for invalid inputs like this rather than relying on the built-in error message for <=

"""
if n < 0:
n = -n
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__":
print(perfect_cube(27))
print(perfect_cube(4))
import doctest

doctest.testmod()