Square Root Of Given Number In Java Without Built-in Functions
Chapter:
Interview Programs
Last Updated:
14-06-2016 14:03:07 UTC
Program:
/* ............... START ............... */
public class JavaSquareRootWithOutBuiltInFunction {
public static void main(String[] args) {
double number = 36;
findSquareRoot(number);
}
public static void findSquareRoot(double number) {
boolean isPositiveNumber = true;
double g1;
if (number == 0) {
System.out.println("Square root of " + number + " = " + 0);
}
else if (number < 0) {
number = -number;
isPositiveNumber = false;
}
double squareRoot = number / 2;
do {
g1 = squareRoot;
squareRoot = (g1 + (number / g1)) / 2;
} while ((g1 - squareRoot) != 0);
if (isPositiveNumber) {
System.out.println("Square roots of " + number + " are ");
System.out.println("+" + squareRoot);
System.out.println("-" + squareRoot);
}
else {
System.out.println("Square roots of -" + number + " are ");
System.out.println("+" + squareRoot + " i");
System.out.println("-" + squareRoot + " i");
}
}
}
/* ............... END ............... */
Output
Square roots of 36.0 are
+6.0
-6.0
Tags
Square Root Of Given Number Without Built-in Functions, Java, Interview Programs