Following Code Calculate The Square Root of a Number Without using sqrt function:
Code::
import java.util.*;
public class Squareroot
{
public static void main(String[] nt)
{ Scanner in=new Scanner(System.in);
double beg=0,end,n;
System.out.print("Enter Number:");
n=in.nextDouble();
end=n;
double prevmid=0,mid=(beg+end)/2;
double dif=Math.abs(mid-prevmid);
while(mid*mid!=n&&dif>0.000005)
{
if(mid*mid>n)
{
end=mid;
}
else
{
beg=mid;
}
prevmid=mid;
mid=(beg+end)/2;
dif=Math.abs(mid-prevmid);
}
System.out.println("Square Root is: "+mid);
}
}
Output::
Code::
import java.util.*;
public class Squareroot
{
public static void main(String[] nt)
{ Scanner in=new Scanner(System.in);
double beg=0,end,n;
System.out.print("Enter Number:");
n=in.nextDouble();
end=n;
double prevmid=0,mid=(beg+end)/2;
double dif=Math.abs(mid-prevmid);
while(mid*mid!=n&&dif>0.000005)
{
if(mid*mid>n)
{
end=mid;
}
else
{
beg=mid;
}
prevmid=mid;
mid=(beg+end)/2;
dif=Math.abs(mid-prevmid);
}
System.out.println("Square Root is: "+mid);
}
}
Output::