One of the most popular frequently asked Java Interview Question is, “Given an integer x, write a java program to find the square root of it”. There are many ways to solve this problem. In this article, let’s check out different ways to find square and square root in Java.
- What is Square and Square Root?
- How to Square a Number in Java
- By multiplying the number by itself
- Using the Math.pow function
- How to Find Square Root of a Number in Java
- Using java.lang.Math.sqrt() method
- By using Math.pow() function
- Without using any inbuilt functions
Before discussing the square root code in Java, let’s understand the term square root first.
The square of a number is that number times itself. In other terms, when we multiply an integer by itself we call the product the square of the number. Mathematically, the square of a number is given as,
Square of n = n*n
For example, the square of number 4 is 4*4 = 16
The square root is just the opposite of the square. The square root of a number, n, is the number that gives n when multiplied by itself. Mathematically, the square root of a number is given as,
Square Root of n = √n
Now that you know what square and square root of a number are, let’s see different ways to calculate them in Java.
How to Square a Number in Java
You can square a number in Java in two different ways:
- Multiply the number by itself
- Call the Math.pow function
Method1: Square a number by multiplying it by itself
Here’s a Java Program to square a number by multiplying it by itself.
package MyPackage; import java.util.Scanner; public class Square1 { public static void main(String args[]) { Double num; Scanner sc= new Scanner(System.in); System.out.print("Enter a number: "); num=sc.nextDouble(); Double square = num*num; System.out.println("Square of "+ num + " is: "+ square); } }
Output
Enter a number: 10 Square of 10.0 is: 100.0
Method2: Square a number with the Math.pow method
Here’s a Java Program to call the Math.pow method to square a number.
package MyPackage; import java.util.Scanner; import java.lang.Math; public class Square2 { public static void main(String args[]) { Double num; Scanner sc= new Scanner(System.in); System.out.print("Enter a number: "); num = sc.nextDouble(); Double square = Math.pow(num, 2); System.out.println("Square of "+ num + " is: "+ square); } }
Output
Enter a number: 22 Square of 22.0 is: 484.0
Now let’s check out how to calculate the square root of a number in Java.
How to Find Square Root of a Number in Java
There are multiple ways to find square root a given number in Java. Let’s explore a few of those.
Method1: Java Program to Find the square root of a Number using java.lang.Math.sqrt() method
Syntax
public static double sqrt(double x)
- Parameter: x is the value whose square root is to be returned.
- Return: This method returns the square root value of the argument passed to it.
- If parameter x is positive double value, this method will return the square root of x
- When x is NaN or less than zero, this method will return NaN
- If parameter x is positive infinity, this method will return positive Infinity
- When x is positive or negative zero, this method will return the result as Zero with the same sign
Code
package MyPackage; public class SquareRoot2 { public static void main(String args[]) { double a = 100; System.out.println(Math.sqrt(a)); // Input positive value, Output square root of x double b = -81.00; System.out.println(Math.sqrt(b)); // Input negative value, Output NaN double c = 0.0/0; // Input NaN, Output NaN System.out.println(Math.sqrt(c)); double d = 1.0/0; // Input positive infinity, Output positive infinity System.out.println(Math.sqrt(d)); double e = 0.0; // Input positive Zero, Output positive zero System.out.println(Math.sqrt(e)); } }
Output
10.0 NaN NaN Infinity 0.0
Method2: Java Program to Find the square root of a Number using java.lang.Math.pow() method
We can use the logic √number = number½ to find the square root of a number.
Code
package MyPackage; import java.util.Scanner; public class SquareRoot1 { public static void main(String[] args) { Double num; Scanner sc= new Scanner(System.in); System.out.print("Enter a number: "); num = sc.nextDouble(); Double squareroot = Math.pow(num, 0.5); System.out.println("The Square of a Given Number " + num + " = " + squareroot); } }
Output
Enter a number: 81 The Square of a Given Number 81.0 = 9.0
Method3: Java Program to Find the square root of a Number without using any in-built method
Here’s the logic that we are using:
The first sqrt number should be the input number / 2. Here’s a Java Program implementing the above logic.
Code
package MyPackage; public class SquareRoot { public static double square(double number){ double t; double squareroot = number / 2; do { t = squareroot; squareroot = (t + (number / t)) / 2; } while ((t - squareroot) != 0); return squareroot; } public static void main(String[] args) { double number = 16; double root; root = square(number); System.out.println("Number : "+number); System.out.println("Square Root : "+root); } }
Output
Number : 121.0 Square Root : 11.0
This brings us to the end of this article.
Make sure you practice as much as possible and revert your experience.
Check out the Java Certification Course Online by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.
Got a question for us? Please mention it in the comments section of this ‘Java sqrt() Method’ article and we will get back to you as soon as possible or you can also join Java Training in Dubai.
Зачастую при написании программ необходимо выполнять какие-то математические операции. Мы уже познакомились с простыми арифметическими — сложение, умножение и т. д. Но что если задача заключается, например, в нахождении квадратного корня из числа (прям как в домашнем задании, где нужно найти корни уравнения)? Ну можно конечно взять всю крутость математического аппарата и написать свою реализацию.
In this tutorial, we will learn about the Java Math.sqrt() method with the help of examples.
The sqrt()
method returns the square root of the specified number.
Example
class Main {
public static void main(String[] args) {
// compute square root of 25
System.out.println(Math.sqrt(25));
}
}
// Output: 5.0
Syntax of Math.sqrt()
The syntax of the sqrt()
method is:
Math.sqrt(double num)
Here, sqrt()
is a static method. Hence, we are accessing the method using the class name, Math
.
sqrt() Parameters
The sqrt()
method takes a single parameter.
- num — number whose square root is to be computed
sqrt() Return Values
- returns square root of the specified number
- returns NaN if the argument less than 0 or NaN
Note: The method always returns the positive and correctly rounded number.
Example: Java Math sqrt()
class Main {
public static void main(String[] args) {
// create a double variable
double value1 = Double.POSITIVE_INFINITY;
double value2 = 25.0;
double value3 = -16;
double value4 = 0.0;
// square root of infinity
System.out.println(Math.sqrt(value1)); // Infinity
// square root of a positive number
System.out.println(Math.sqrt(value2)); // 5.0
// square root of a negative number
System.out.println(Math.sqrt(value3)); // NaN
// square root of zero
System.out.println(Math.sqrt(value4)); // 0.0
}
}
In the above example, we have used the Math.sqrt()
method to compute the square root of infinity, positive number, negative number, and zero.
Here, Double.POSITIVE_INFINITY
is used to implement positive infinity in the program.
When we pass an int value to the sqrt()
method, it automatically converts the int
value to the double
value.
int a = 36;
Math.sqrt(a); // returns 6.0
Recommended Tutorials
- Java Math.pow()
- Java Math.cbrt()
Overview
Math.sqrt() method of java.lang package is used to find the correctly rounded and positive square root of a given number in Java.
This method takes double as an argument and returns a variable of double type. There are various special cases where it returns particular values as per the input. Also, we can implement our own square root method using a mathematical formula and using the Math.pow() method.
We can also find the square root of BigInteger whose range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 with the help of the inbuilt sqrt() method of the respective class.
Scope of Article
- This article explains sqrt in Java, its parameters, syntax, return values, and examples.
- We will also learn to find square root using Math.pow() method and implementation of sqrt method. We will also discuss BigInteger.sqrt() method in Java.
Introduction
The Math.sqrt() in Java is present in java.lang.Math class and is used to calculate the square root of the given number. It returns the double value that is correctly rounded positive square root of a given double value. In case of negative number input it returns NaN(Not a Number) as square root of negative number are not real but imaginary numbers. Since it is a static method we can directly call it using its class name like Math.sqrt().
Method Declaration of Math.sqrt() Method in Java
Math.sqrt() method in Java is declared as follows:
public static double sqrt(double num);
It is a static method i.e. can be directly called using Math class.
Syntax of Math.sqrt() in Java
To find the square root of a number we use the following syntax, pass the number num to sqrt() method. Also, num can be of the type int,float, or double. Lastly, we can store the result in another variable of Double type.
double result = Math.sqrt(num);
Parameters of Math.sqrt() in Java
Math.sqrt() method takes a single variable of double data type whose square root we are supposed to find.
Return Values of Math.sqrt() in Java
Math.sqrt() method returns a double value which is the square root of the given value and is a correctly rounded positive number. If the argument is NaN or a negative number, it returns NaN i.e. Not a Number.
Examples of Math.sqrt() Method in Java
Let us see an example for finding the square root of the user entered number.
import java.util.Scanner; public class Main { public static void main(String args[]) { // user input Scanner sc = new Scanner(System.in); System.out.println("Enter a number"); double num = sc.nextDouble(); // finding square root of the user entered number double squareRoot = Math.sqrt(num); System.out.println("Square root of " + num + " is " + squareRoot); sc.close(); } }
Output:
Enter a number 40 Square root of 40.0 is 6.324555320336759
Explanation:
We store the user-entered value into the num variable of double type, which is passed to the Math.sqrt() method. Math.sqrt() method returns a double value which is stored in squareRoot variable and printed.
Example: Special Cases
There are various special cases where we might expect a different value for instance say square root of infinity or a negative number.
Note : NaN stands for Not a Number in Java. It is a special floating-point value that denotes overflows and errors. It is generated in the cases where a floating-point number is divided by zero or the square root of a negative number is computed as square root of negative numbers result in imaginary numbers.
Let us consider these five special cases:
- Zero(0) — It returns 0.0 (zero as a double value) as a square root of 0.
- Negative Integer — It return NaN as square root of negative number is a complex number.
- Positive Infinity — It returns Infinity.
- Negative Infinity — As it is infinity but still a negative number it returns NaN.
- NaN — Square root of NaN is returned as NaN itself.
Let us verify the outputs using a Java program:
class Main { public static void main(String args[]) { // for zero(0) System.out.println(Math.sqrt(0)); // negative number System.out.println(Math.sqrt(-100)); // negative infinity System.out.println(Math.sqrt(Double.NEGATIVE_INFINITY)); // positive infinity System.out.println(Math.sqrt(Double.POSITIVE_INFINITY)); // NaN System.out.println(Math.sqrt(Double.NaN)); } }
Output:
As we can see in the above example, it returns NaN for NaN or negative numbers, or negative Infinity as arguments. It returns 0.0 for 0 as an argument and Infinity for Double.POSITIVE_INFINITY as an argument.
Working of Math.sqrt() in Java
The square root of a number in Java is calculated using simple arithmetic operations such as addition, subtraction, multiplication, and division. And lastly, with the help of loops, we get the desired answer. The mathematical formula used to find the square root precisely is given below.
Algorithm for Finding Square Root of a Number in Java
We firstly take two variables num and half. num is left uninitialized and half is initialized as value/2. We run a do-while loop, inside do-while loop we initialized num=half each time the loop runs, and half = (num + value/num) where value is user-entered number. We run this loop until num is not equal to half. As this condition satisfies half is the required square root of value.
Let us apply it to the Java code.
public class Main { public static double SquareRoot(double value){ double num; double half = (double) value / 2; do { num = half; half = (num + (value / num)) / 2; } while ((num - half) != 0); return half; } public static void main(String[] args){ double num = 49; System.out.println("Square root of "+num+" is "+SquareRoot(num)); } }
Output:
The square root of 49.0 is 7.0
Square root using pow() method
There are other ways to find the square root of a number in Java except for the Math.sqrt() method. The first one we saw in the previous example by implementing our own method that calculates the square root of a number. Another way is using the Math.pow() method which is located in the same package as Math.sqrt() i.e. java.lang.
The square root is nothing but a number to the power 1/2 (0.5 or half). We can pass 0.5 or 1/2 as the power to Math.pow() to get the square root of a number.
Let us see this example to compare Math.pow() and Math.sqrt() methods in Java.
import java.util.Scanner; class Main { public static void main(String args[]) { // taking user input Scanner sc = new Scanner(System.in); System.out.println("Enter a number"); double num = sc.nextDouble(); // square root using Math.sqrt() double squareRoot_sqrt = Math.sqrt(num); // square root using Math.pow() double squareRoot_pow = Math.pow(num, 0.5); System.out.println( "Square root of " + num + " is " + squareRoot_sqrt + " using Math.sqrt method" ); System.out.println( "Square root of " + num + " is " + squareRoot_pow + " using Math.pow method" ); sc.close(); } }
Output:
Enter a number 7283.7824 Square root of 7283.7824 is 85.34507835839159 using Math.sqrt method Square root of 7283.7824 is 85.34507835839159 using Math.pow method
Explanation:
In the example, we first ask for user input, which we later pass to both the methods i.e. Math.sqrt and Math.pow() with power being 0.5. We can see that both the methods return the same answer.
BigInteger sqrt() Method
BigInteger in Java is used where big integer calculations are required that are outside the range of integer or long data type. java.math.BigInteger.sqrt() method returns BigInteger that is square root of the given BigInteger. It is just same as floor(sqrt(num)) i.e. it returns a floor value unlike Math.sqrt() that returns a double(numbers after decimal).
Syntax
Syntax of sqrt in java of BigInteger is little different from that of Math.sqrt(). It takes no parameter, it can be only called using objects of BigInteger class and it returns the floor value of the square root of the respective BigInteger.
BigInteger bg = num.sqrt();
The below example illustrates the sqrt() method of BigInteger class.
import java.math.BigInteger; class Main { public static void main(String args[]) { BigInteger num = new BigInteger("7679038450928389294"); BigInteger squareRoot = num.sqrt(); System.out.println("Square root of " + num + " is " + squareRoot); } }
Output:
Square root of 7679038450928389294 is 2771107802
Explanation:
- The num is a variable of BigInteger type which has 19 digits. The value of num variable cannot be stored in an Integer or Long type variable.
- num.sqrt() returns a BigInteger that is the square root of num and is stored in squareRoot.
- Again the square root of the given number is big enough that it cannot be stored in int data type.
Conclusion
- Math.sqrt() in Java is a method using which we can find the square root of any number of double types with precision.
- It is present in java.lang.Math class.
- The sqrt() method in Java takes a double type variable and also returns a positive double value which is the square root of the argument and is correctly rounded.
- It returns NaN when the argument is Negative or NaN. It returns 0.0 and infinity for arguments 0 and positive infinity respectively.
- Java provides two other ways to calculate the square root of a number, one of which is using the Math.pow() method with power being 0.5 and we can also implement our own method for finding square root using simple arithmetic operations and loops.
- We can also find the square root of a BigInteger. java.math.BigInteger class contains sqrt() method that returns floor value of BigInteger type that is the square root of the given BigInteger.
Описание
Метод Math.sqrt() – возвращает квадратный корень из аргумента.
Синтаксис
double sqrt(double d)
Параметры
Подробная информация о параметрах:
- base – любой примитивный тип данных.
- exponent – любой примитивный тип данных.
Возвращаемое значение:
- В Java Math.sqrt() возвращает квадратный корень из аргумента.
Пример
public class Test{
public static void main(String args[]){
double x1 = 16;
double x2 = 2.25;
double x3 = 0.25;
double x4 = 88.675;
System.out.printf("sqrt(%.3f) = %.3f%n", x1, Math.sqrt(x1));
System.out.printf("sqrt(%.3f) = %.3f%n", x2, Math.sqrt(x2));
System.out.printf("sqrt(%.3f) = %.3f%n", x3, Math.sqrt(x3));
System.out.printf("sqrt(%.3f) = %.3f%n", x4, Math.sqrt(x4));
}
}
Получим следующий результат:
sqrt(16,000) = 4,000
sqrt(2,250) = 1,500
sqrt(0,250) = 0,500
sqrt(88,675) = 9,417