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

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -