Problem statement: Find the square root of a number in java !
1st Approach:
public class SquareRootExe {
public static void main(String args[]) {
double sqrRoot = squareRoot(4);
System.out.println(sqrRoot);
}
public static double squareRoot(double n) {
double t;
double sqRoot = n / 2;
do {
t = sqRoot;
sqRoot = (t + (n / t)) / 2;
} while ((t - sqRoot) != 0);
return sqRoot;
}
}
2nd Approach:
public class SquareRootExe {
public static void main(String args[]) {
double sqrRoot = squareRoot(4);
System.out.println(sqrRoot);
}
public static double squareRoot(double n) {
double res = Math.sqrt(n);
return res;
}
}
Output:
2.0
1st Approach:
public class SquareRootExe {
public static void main(String args[]) {
double sqrRoot = squareRoot(4);
System.out.println(sqrRoot);
}
public static double squareRoot(double n) {
double t;
double sqRoot = n / 2;
do {
t = sqRoot;
sqRoot = (t + (n / t)) / 2;
} while ((t - sqRoot) != 0);
return sqRoot;
}
}
2nd Approach:
public class SquareRootExe {
public static void main(String args[]) {
double sqrRoot = squareRoot(4);
System.out.println(sqrRoot);
}
public static double squareRoot(double n) {
double res = Math.sqrt(n);
return res;
}
}
Output:
2.0
No comments:
Post a Comment