A little suggestion about solution 12.6 in 1.4.7

#1

We could follow the fashion of solution 12.1 and 12.2, which is when square < x, assign mid to res and do left = mid + 1. The readability is higher as in every iteration we are trying to keep the local optimum and the rest is just the classic binary search, v.s. the current solution which has special logic with the while condition, mid inclusion and right*right check at the end. Thoughts?

btw if you run the code on Windows, where int = long, it could overflow. Use double for mid and square_m instead.

0 Likes

#2

Hey Ray,

Many thanks to your brilliant idea! It not only removes the special logic after while condition but also removes the special case in the beginning of program.

About the issue where int = float on Window, since ANSI standard won’t have such problem, let’s just pray the Windows compiler updates anytime soon :wink:

0 Likes

#3

Cool. Sorry I meant to say int = long, although float is also 4 bytes on Windows. Edited my OP.

0 Likes