python 3.x - Binary search goes into infinite loop -


i'm trying find if number perfect square. have simple binary search algorithm this, ends going infinite loop. can't seem find way around this. can me this.

def isperfectsquare(self, num):         """         :type num: int         :rtype: bool         """         if num < 1:             return false         start, end = 1, num         while start <= end:             mid = (end - start)//2             if mid * mid == num:                 return true             elif mid * mid < num:                 start = mid + 1             else:                 end = mid         return false 

i kind of found problem, line of code ends wrong mid,

mid = (end - start)//2

since want mid in correct half, code be,

mid = start + (end - start) // 2 fixes it.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -