OneCompiler

Problem 3 Complexity: Medium You have to find square root of a given positive integer. If it is not a perfect square, compute the square root to a precision of 3 digits after decimal point. You cannot use predefined functions for computing the square root. Multiple solutions to solve this would be considered a plus.

392

import java.util.*;
public class Problem3 {

public static double squareRoot(int number) {
double temp;

double sr = number / 2;

do {
	temp = sr;
	sr = (temp + (number / temp)) / 2;
} while ((temp - sr) != 0);

return sr;
}

public static void main(String[] args) {
	System.out.print("Enter any number:");
	Scanner scanner = new Scanner(System.in);
	int num = scanner.nextInt(); 
	scanner.close();

	System.out.println("Square root of "+ num+ " is: "+squareRoot(num));

}

}