Skip to content

Commit 25ccc0d

Browse files
ihebustokhos
authored andcommitted
Perfect square using binary search (TheAlgorithms#2351)
* Add perfect_square_binary_search * Update tests * Add tests
1 parent 1af6d68 commit 25ccc0d

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

maths/perfect_square.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,52 @@ def perfect_square(num: int) -> bool:
2121
return math.sqrt(num) * math.sqrt(num) == num
2222

2323

24+
def perfect_square_binary_search(n: int) -> bool:
25+
"""
26+
Check if a number is perfect square using binary search.
27+
Time complexity : O(Log(n))
28+
Space complexity: O(1)
29+
30+
>>> perfect_square_binary_search(9)
31+
True
32+
>>> perfect_square_binary_search(16)
33+
True
34+
>>> perfect_square_binary_search(1)
35+
True
36+
>>> perfect_square_binary_search(0)
37+
True
38+
>>> perfect_square_binary_search(10)
39+
False
40+
>>> perfect_square_binary_search(-1)
41+
False
42+
>>> perfect_square_binary_search(1.1)
43+
False
44+
>>> perfect_square_binary_search("a")
45+
Traceback (most recent call last):
46+
...
47+
TypeError: '<=' not supported between instances of 'int' and 'str'
48+
>>> perfect_square_binary_search(None)
49+
Traceback (most recent call last):
50+
...
51+
TypeError: '<=' not supported between instances of 'int' and 'NoneType'
52+
>>> perfect_square_binary_search([])
53+
Traceback (most recent call last):
54+
...
55+
TypeError: '<=' not supported between instances of 'int' and 'list'
56+
"""
57+
left = 0
58+
right = n
59+
while left <= right:
60+
mid = (left + right) // 2
61+
if mid ** 2 == n:
62+
return True
63+
elif mid ** 2 > n:
64+
right = mid - 1
65+
else:
66+
left = mid + 1
67+
return False
68+
69+
2470
if __name__ == "__main__":
2571
import doctest
2672

0 commit comments

Comments
 (0)