The square root of a number is equal to (number1/2) or (number0.5) and is denoted using the symbol “√”. For example, the square root of 25 is 5 (i.e., 250.5 = 5). Finding the square root of a number in Java is a common task that can be achieved by invoking built-in methods like “Math.pow()” and “Math.sqrt()”. Also, you can use the brute force or binary search algorithm to find the square root of a number.
This post uses different examples to explain how to find the square root of a number with or without using the built-in methods in Java.
Content Overview
- How to Find the Square Root of a Number in Java Using Built-in Methods
- Method 1: Math.sqrt()
- Method 2: Math.pow()
- How to Find the Square Root of a Number in Java Using Custom Methods
- Method 1: Brute Force(Iterative Approach)
- Method 2: Binary Search Algorithm
- How to Find the Square of a Number in Java
Let’s get started with the built-in methods.
How to Find the Square Root of a Number in Java Using Built-in Methods
Math is a built-in static class in Java that offers several methods to perform mathematical operations. For example, to find/compute the square root of a numeric value, you can use the built-in “sqrt()” and “pow()” methods. Both these methods are explained below with appropriate examples.
Method 1: Using Math.sqrt()
The “Math.sqrt()” method accepts a positive numeric value as an argument and retrieves its square root. In the following example, we use this method on several double-type numbers to find their respective square roots:
public class SquareRootJava {
public static void main(String args[])
{
double positiveNum = 144;
double negativeNum = -100.00;
double zero = 0.0;
double zeroByZero = 0.0/0.0;
double numByZero = 49.0/0.0;
System.out.println("Square Root of Positive Number == " + Math.sqrt(positiveNum));
System.out.println("Square Root of Negative Number == " + Math.sqrt(negativeNum));
System.out.println("Square Root of Zero == " + Math.sqrt(zero));
System.out.println("Square Root of zeroByZero == " + Math.sqrt(zeroByZero));
System.out.println("Square Root of numByZero == " + Math.sqrt(numByZero));
}
}
We declare five double-type variables in this code and assign them different values. The first variable is initialized with a positive value, the second one is initialized with a negative value, and the third one is initialized with 0. While the remaining two variables are initialized with fractional values. We invoke the sqrt() method on each value and print the corresponding square roots on the console:
Method 2: Using Math.pow()
The “Math.pow()” is a static method of the “java.lang.Math” class. It accepts two double-type parameters: “base” and “exponent”. It retrieves the output as (baseexponent). You can invoke this method on a positive number to find/compute its square root. To do that, you must specify/use the exponent value as “0.5”, as we did in the below code:
public class SquareRootJava {
public static void main(String args[])
{
double positiveNum = 121;
double negativeNum = -121.00;
double zero = 0.0;
double zeroByZero = 0.0/0.0;
double numByZero = 49.0/0.0;
System.out.println("Square Root of Positive Number == " + Math.pow(positiveNum, 0.5));
System.out.println("Square Root of Negative Number == " + Math.pow(negativeNum, 0.5));
System.out.println("Square Root of Zero == " + Math.pow(zero, 0.5));
System.out.println("Square Root of zeroByZero == " + Math.pow(zeroByZero, 0.5));
System.out.println("Square Root of numByZero == " + Math.pow(numByZero, 0.5));
}
}
In the above code, we declare and initialize five double-type variables. After this, we invoke the “Math.pow()” method with “0.5” as its second argument. On successful execution of the code, we get the following results:
How to Find the Square Root of a Number in Java Using Custom Methods
Other than built-in methods, you can customize your logic to find any given number’s square root. For this purpose, either you can use the brute force or the binary search algorithm.
Method 1: Using Brute Force(Iterative Approach)
Create a user-defined function that returns a double-type value (indicating the square root of the input number). Within this function, create a temporary variable of type double to store the square root of the given number. Declare another double-type variable and initialize it with “inputNum/2”. Now use a do-while loop to compute the square root of the specified/given value. For this purpose, use the formula: “sqrt = (temp + (inputNum / temp)) / 2” within the do-while loop. The loop continues until the difference between the previous value of sqrt (temp) and the current value of sqrt is zero. Finally, it returns the calculated square root value:
import java.util.Scanner;
public class SquareRootJava {
public static double findSquareRoot(double inputNum) {
double temp;
double sqrt = inputNum / 2;
do {
temp = sqrt;
sqrt = (temp + (inputNum / temp)) / 2;
} while ((temp - sqrt) != 0);
return sqrt;
}
public static void main(String[] args) {
double inputNum = 0, result = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number to Compute Sqrt ==> ");
inputNum = scan.nextDouble();
sqRoot= findSquareRoot(inputNum);
System.out.println("The Square Root of the Given Number is ==> " + sqRoot);
scan.close();
}
}
In the main() method, we use the nextDouble() method to input a number from the user. After this, the findSquareRoot() function is invoked with the user-entered number to find its square root:
The output shows the computed square roots of the given values.
Method 2: Using Binary Search
In this section, we will explain how to compute the square root of a number in Java using the binary search algorithm. We split the code into three chunks: two user-defined functions and a main() method. The first user-defined function “perfectSquareRoots()” checks if the specified number/value is a perfect square or not. If the given number is a perfect square it returns 1, otherwise it invokes the “decimalSquareRoot()” function to find the square root and returns it:
import java.util.Scanner;
public class SquareRootJava {
private static double perfectSquareRoot(double inputNum) {
int x = 1;
while (true) {
if (x * x == inputNum)
return x;
else if (x * x > inputNum)
return decimalSquareRoot(inputNum, x - 1, x);
x++;
}
}
private static double decimalSquareRoot(double inputNum, double x, double y) {
double midNum = (x + y) / 2;
double square = midNum * midNum;
if (square == inputNum || Math.abs(square - inputNum) < 0.0000001)
return midNum;
else if (square > inputNum)
return decimalSquareRoot(inputNum, x, midNum);
else
return decimalSquareRoot(inputNum, midNum, y);
}
public static void main(String[] args) {
double inputNum = 0, result = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number to Compute Sqrt ==> ");
inputNum = scan.nextDouble();
sqRoot = perfectSquareRoot(inputNum);
System.out.println("The Square Root of the Given Number is ==> " + sqRoot);
scan.close();
}
}
The decimalSquareRoot() function uses the binary search algorithm to calculate the square root of the decimal numbers. In this function, first, we find the mid-value of the two given numbers x and y. After this, we calculate the square of the computed mid-value and store it in a variable “square”. Next, we use the if statement to check if the square of midNum is equal to the inputNum, or if the absolute difference between the square of midNum and inputNum is less than the “0.0000001”. If any of the conditions is true, it returns the midNum as the square root of the number. If the square of the midNum is greater than or less than the input number, it recursively calls the decimalSquareRoot() function to find the square root:
The output illustrates that the defined function successfully retrieves the perfect as well as decimal square roots.
How to Find/Compute the Square of a Number in Java
A built-in “Math.pow()” function is used with “2” as its second argument to find the square of a number in Java. Other than this function, you can also use the “*” operator to calculate the square of a number in Java. The below code implements both these approaches in Java to find the square of the number “12”:
public class SquareRootJava {
public static void findSquare(double inputNum) {
inputNum = inputNum * inputNum;
System.out.println("Square Using * Operator ==> " + inputNum);
}
public static void main(String[] args) {
double inputNum = 12;
findSquare(inputNum);
System.out.println("Square Using Math.pow() ==> " + Math.pow(inputNum, 2));
}
}
From the main() method, we invoke both the user-defined “findSquare()” and pre-defined “Math.pow()” function to get the square of given number:
That’s all about finding the square root of a number in Java.
Conclusion
To find the square root of a number in Java, use methods like “sqrt()”, “pow()”, “binary search algorithm”, or “brute force”. The “sqrt()” and “pow()” are built-in methods of Java’s Math class while the other two approaches are used to build custom logic. In Java, the sqrt() method is specifically used to find the square root of a number, however, the pow() method can be used to calculate the square root or power of any given number. Other than these built-in methods, we’ve also discussed a couple of custom methods that can be used to find the square root of a number in Java.