Created
April 11, 2026 06:52
-
-
Save thinkphp/36976b01b8bd22a1fcb0b546b3288f9c to your computer and use it in GitHub Desktop.
Babylonian-SQRT.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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