20-CS-122-001 Computer Science II Spring 2012
Sqrt class

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev     Next     Lectures     sqrt.cc     sqrt1.cc     sqrt2.cc     rational.h     rational.cc

// Calculate square roots
// The algorithm:
//  Let the number be n
//  Set m = n
//  Repeat the following for as long as you wish
//     m = (m+n/m)/2
// 
//  Notice, if this converges, that 2m = m + n/m or
//  m = n/m or m^2 = n
#include <iostream>
#include "rational.h"
using namespace std;

int main (int argc, char **argv) {
   if (argc != 2) {
      cerr << "Usage: " << argv[0] << " \n";
      exit(0);
   }

   Rational *m = new Rational(atoi(argv[1]));
   Rational *n = new Rational(atoi(argv[1]));
   Rational *t = new Rational(0);
   int i=0;
   for ( ; i < 100 && !(m->truncate_p(30))->equals(t) ; i++) {
      m->show(30);
      t = m->truncate_p(30);
      m = &(((*n)/t + t)/2);
   }
   cout << "\nAnswer: ";  m->show(30); cout << " (" << i << ")\n";
}