// if you know that the square root of X must be somewhere // between A and B, guess that it might be at the mid-point // G = (A+B)/2, and see which side of G the correct answer // must be. // Asking if G < square_root(X) which is what we want to do, // is the same as asking if G*G < X, which is very easy to // do. // If the guess turns out to be too big, then search for the // square root of X between A and G. If G was too small, search // between G abd B. It has to be somewhere in there. // Except // If A and B (the numbers you know the suare root must be // between) are really really close together, depending on how // much accuracy you want, their average will be good enough. #include "library.h" const double accuracy = 0.000001; double search_for_sqrt(const double x, const double min, const double max) { if (max-min < accuracy) return (min+max)/2; else { const double guess = (min+max)/2; if (guess*guess == x) return guess else if (guess*guess > x) return search_for_sqrt(x, min, guess); else return search_for_sqrt(x, guess, max); } } void main() { print(search_for_sqrt(2, 0, 10)); } // naturally, you wouldn't want to have to use such a clumsy function call // every time you want the square root of something. So you would realise // that all reasonable numbers are bigger than their own square roots, so // you always know a maximum for the search. Unreasonable numbers (those // that are <= 1) all have square roots <= 1, so you would define double square_root(const double x) { return search_for_sqrt(x, 0, x+1); }