Binary search.
#include <vector>
#include <iostream>
using namespace std;
int sqrt(int x) {
long long left = 0;
long long right = x;
long long xx = x;
while(left < right) {
long long mid = (left + right) / 2;
if(mid * mid <= xx && (mid + 1)* (mid + 1) > xx) {return (int) mid;}
if(mid * mid < xx) left = mid + 1;
else if(mid * mid > xx) right = mid - 1;
}
}
int main(void) {
int sq = sqrt(4);
cout << sq << endl;
}
An algorithm named Babylonian method. Suppose we want to get 10's square root. First guess the result is 5. and then verify it.
5 != 0 ---> we get the next closer number: (5 + 10 / 5 ) /2 = 3, verify that 3 ! 5, we get the next closer number: (3 + 10 / 3 ) / 2 == 3, return 3. This method best works for double class.
double SQRT(const double fg) {
double n = fg / 2.0;
double lstx= 0.0;
while(n != lstx) {
lstx = n;
n = (n + fg/n) / 2.0;
}
return n;
}