mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Add perfect cube binary search (#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>
This commit is contained in:
parent
abc390967d
commit
a9cee1d933
|
@ -11,6 +11,45 @@ def perfect_cube(n: int) -> bool:
|
||||||
return (val * val * val) == n
|
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: perfect_cube_binary_search() only accepts integers
|
||||||
|
>>> perfect_cube_binary_search(0.1)
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
TypeError: perfect_cube_binary_search() only accepts integers
|
||||||
|
"""
|
||||||
|
if not isinstance(n, int):
|
||||||
|
raise TypeError("perfect_cube_binary_search() only accepts integers")
|
||||||
|
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__":
|
if __name__ == "__main__":
|
||||||
print(perfect_cube(27))
|
import doctest
|
||||||
print(perfect_cube(4))
|
|
||||||
|
doctest.testmod()
|
||||||
|
|
Loading…
Reference in New Issue
Block a user