Math Fundamentals18 sections · 814 units
Open in Course

Valid Perfect Square - Binary Search

Narrowing the range

The squares 12,22,32,...1^2, 2^2, 3^2, ... form an increasing sequence. This means you can use binary search.

Start with left=1left = 1 and right=numright = num. Compute midmid and check mid2mid^2. If mid2=nummid^2 = num, you found it. If mid2<nummid^2 < num, search the right half. If mid2>nummid^2 > num, search the left half.

Watch out for overflow when computing mid2mid^2. If midmid is large, the product might exceed integer limits.