// // FILE: binsqrt.cpp // Author: Leo Reyzin // Purpose: code to take in an integer and find its integer square root // HW3 of CS112B1 Spring 2003 // #include using namespace std; // Outputs the integer square root of x, that is, // the largest integer y such that y*y<=x. // For example, binsqrt(0)=0, binsqrt(5)=2, binsqrt(9)=3. unsigned int binsqrt(unsigned int x) { unsigned int low=0, high=x+1, mid; // invariant: at the beginning of each loop iteration // high must always be greater than the real // square root of x, while low must always be less than or equal // to the real square root of x. // This is why high is set to x+1 above -- else, for x=0 or 1, // it would be equal to sqrt x, not greater than while (low x) high = mid; // Note that high remains greater than the real root of x else low = mid; // Note that low remains less than or equal to real root of x } // We are now guaranteed that high=low+1, and the real root of x // is in the interval [low,high[ So low is the right thing to output return low; } int main() { unsigned int x; cin >> x; cout << binsqrt(x) <<'\n'; return 0; }