Skip to content

Add perfect cube binary search #10477

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
35 changes: 33 additions & 2 deletions maths/perfect_cube.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,37 @@ 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 <=

"""
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()