Thursday, April 23, 2015

Finding square root of a value.

class findsqrt
{
  public static void main(String args[])
  {
    int x;
    if(args.length<1)
    {
      System.out.println("java findsqrt ###");
      System.exit(0);
    }
    x=Integer.parseInt(args[0]);
    double up,down,middle=0;
    //Finding the upper range value
    for(up=1;up<=200;up++)
       if(up*up> x) break;
    down=up-1;
    int i;
    for(i=0;i<15;i++)
    {
       middle=(up+down)/2.0;
       if(middle*middle>x)
         up=middle;
       else
         down=middle;
       System.out.println(down +"\t"+ middle +"\t"+ up);
    }
    System.out.println("Sqrt = " + middle);
  }
}