Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created April 11, 2026 06:52
Show Gist options
  • Select an option

  • Save thinkphp/36976b01b8bd22a1fcb0b546b3288f9c to your computer and use it in GitHub Desktop.

Select an option

Save thinkphp/36976b01b8bd22a1fcb0b546b3288f9c to your computer and use it in GitHub Desktop.
Babylonian-SQRT.cpp
#include <iostream>
using namespace std;
//Divide Et Impera
double babylonianSquareRoot(double number)
{
if(number < 0) {
cerr<<"Error: Cannot compute Square Root of a negative number."<<endl;
return -1;
}
double x = number; //initial
double y = 1.0;
double e = 0.000001; //tolerance for convergence
while((x - y) > e) {
x = (x + y) / 2.0; //update X as the average of x and y;
y = number / x;
}
return x;
}
int main(int argc, char const *argv[])
{
double number;
cout<<"Enter a number to compute its Square Root: ";
cin>>number;
double result = babylonianSquareRoot( number );
if( result != -1 ) {
cout<<"The Square Root of "<<number<<" is approximately: "<<result<<endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment