Tag Archives: #WSQ10

Homework 10: Babylonian Method

This function will calculate a square root through the Babylonian Method.

First of all, I would like to explain how the method works. You have to establish a first number that is “aproximate” to the real squareroot, doesn’t matter if that number is equal to one, because we are going to make some mathematical operations. Shown below the steps.

  1. Divide the number, which we want to calculate its square root (N), between the before established number (y).
  2. The result of the past step will be added to the first established number (y).
  3. We repeat this steps until we obtain the aproximation as exactly as we want it.

Having said that, we only have to create a function that execute this algorithm, and ask the user for the number that he/she wants to calculate its square root.

This is my code.

#include <iostream>
using namespace std;

long double square_root(long double N)
{
  long double y=1, c;
  for(int i=0; i<1000; i++)
  {
    c=N/y;
    y=(y+c)/2;
  }
  return y;
}

int main()
{
  int N;
  cout << "Square Root... \n\nNumber: ";
  cin >> N;
  cout << "The square root of "<< N << " is equal to "<<square_root(N) << endl << endl;
  return 0;
}