(This is an extension of an exercise from Chapter 1.) The Babylonian algorithm to compute the square root of a positive number n is as follows:
1. Make a guess at the answer (you can pick n/2 as your initial guess).
2. Compute r = n / guess.
3. Set guess = (guess + r) / 2.
4. Go back to step 2 for as many iterations as necessary. The more steps 2 and 3 are repeated, the closer guess will become to the square root of n.
Write a program that inputs a double for n, iterates through the Babylonian algorithm until the guess is within 1% of the previous guess, and outputs the answer as a double to two decimal places. Your answer should be accurate even for large values of n.
//Include header files for execute C++ program
#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
//main function
int main()
{
//variables declaration
int n;
double r;
double guess;
double initialGuess;
//Inputs an integer for n, iterates through
//the Babylonian algorithm until guess is
//within 1% of the previous guess and
//outputs the answer as a double
cout<<"Please enter an integer n = ";
cin>>n;
//Calculating value of guess
guess = (double) n/2;
while( guess*guess < 0.99*(double)n ||
guess*guess > 1.01*(double)n)
{
initialGuess = guess;
r = (double) n/guess;
guess = (double)(guess+r)/2;
}
cout << "The square root of a number n ="
<< n <<" is " << guess;
}
Output 1 for the program code:
Please enter an integer n = 555
The square root of a number n =555 is 23.5593
Output 2 for the program code:
Please enter an integer n = 1221
The square root of a number n =1221 is 34.9885