Search for Courses, Topics
certificate icon
Certificate

Learn on Scaler Topics and get certified.

static-certificate

Square Root in Java with Examples

Learn about Finding the Square Root in Java.

28 Jul 2021-9 mins read

As a programmer, I always find it fascinating to write programs for mathematical operations I used to do by hand back in school.

Square and square root of a number is one of the principles which are used in many real-life applications as well as programming concepts, for example prime factors of a number, binary exponentiation etc.

If that doesn’t excite you, they are a hot topic in interviews as well 🙂

Let’s start by defining what a square and square root actually means.

What is Square?

Simply put, the square of a number is the number multiplied by itself. In other words, if we multiply a number by itself, the result is the square of that number.

Square of X = X * X

For example, if X = 3

Square of 3 = 3 * 3 = 9

What is Square Root?

Square root is exactly the opposite of the square of a number. The square root of a number X is the number that when multiplied by itself equals X.

Square root of X = √X

where √ is the symbol for square root

For example, if X = 9

Square root of 9 = √9 = 3

The square root of X can also be represented by X 1/2. This is important, keep reading to find out why 🙂

In a nutshell, if the square of a number X is S, then X is the square root of S.

It’s alright, try to breathe that in for a moment 🙂

Now that we know what we mean by the square and square root of a number, let’s see how we can write a program for it in Java.

How to square a number in Java?

There are a couple of ways to find the square of a number in Java. Let’s look at them one by one.

1. Multiplying the number by itself: It’s as simple as it sounds. Just multiply the number by itself and you’re good to go.

int X = 3;
int S = X * X;
System.out.println("The square of " + X + " is " + S);
// The square of 3 is 9

2. Using Math.pow Method: Math is a utility class in Java that has many useful mathematical functions, one of which is pow which allows you to calculate the exponentiation or power of a number.

Syntax of Square Root in Java:

public static double pow(double base, double exponent);

Parameters: base, exponent

Returns of Square Root in Java: base to the power of exponent

Both parameters accept double as the input. The return type is also a double value.

If you pass an integer or any primitive numerical value to either base or exponent, it will automatically be cast to double in Java.

So, if base = 10, exponent = 2 Math.pow(10, 2) = 100.0

So, in order to find the square of a number, we can pass the base as the number and the exponent as 2. Here’s a snippet that shows the usage of Math.pow.

int X = 3;
double S = Math.pow(X, 2);
System.out.println("The square of " + X + " is " + S);
// The square of 3 is 9.0

How to Find the Square Root of a Number in Java?

Calculating the square of a number was pretty straight forward right. But calculating the square root of a number is a bit more interesting. Let’s see how we can do that.

1. Using Math.sqrt: This is the friendly sibling of the Math.pow function we saw in the previous segment. Like the way it reads, it finds the square root of a number.

Syntax of Square Root in Java:

public static double sqrt(double number);

Parameters: number Returns: The square root of number

The number parameter accepts double as input and the return type is also a double value.

So, if number = 9 Math.sqrt(9) = 3.0

Here’s a snippet that demonstrates the use of Math.sqrt

int X = 9;
double R = Math.sqrt(X);
System.out.println("The square root of " + X + " is " + R);

// The square root of 9 is 3.0

2. Using Math.pow: You: Say, what? Math.pow can be used to find the square root of a number as well?

Rahul: That’s right. Just like we used Math.pow to find the square of a number, we can use it to find the square root of a number as well.

You: But how?

Rahul: Remember the way the square root of a number is represented: X1/2; it means the square root of a number is X to the power of ½.

So if we pass the value of the exponent in Math.pow as 0.5 which is ½, the resulting number will be the square root. Let’s try that in the below snippet.

int X = 9;
double R = Math.pow(X, 0.5);
System.out.println("The square root of " + X + " is " + R);
// The square root of 9 is 3.0

Neat right? The same function is used to calculate two different operations.

3. Without using any inbuilt function Now that we have looked at a few ways to find the square root of a number using inbuilt functions in Java, let’s look at away without using any such inbuilt function.

Let me propose an algorithm first and then we’ll break it down one step at a time.

  • Start from i = 1, if i * i == n, then i is the square root of n as n is a perfect square.
  • if i * i > n, it means the square root must lie between (i-1, i), let’s call them (low, high)
  • Apply binary search in the range (low, high). Find mid of (low, high):
  1. if mid * mid == n, it means we assume that mid is the square root of n
  2. if mid * mid > n, it means that the assumption we made is incorrect. This Implies, that the square root of n must be less than mid, since any value higher than mid can never satisfy the condition mid * mid == n. Hence, we will try to find the square root on the left side of mid by repeating step 3 for (low, mid)
  3. else mid * mid < n, means that the assumption we made is incorrect. This Implies, that the square root of n must be greater than mid since any value less than mid can never satisfy the condition mid * mid == n. Hence, we will try to find the square root on the right side of mid by repeating repeat step 3 for (mid, high)

What is Perfect Square?

A perfect square is an integer that is the square of an integer.

For example:

X = 9 = 3 * 3 = 3^2

Here, 9 is a perfect square because 9 is the square of 3. On the other hand, 10 is not a perfect square because it cannot be represented as the square of an integer.

So, if we want to calculate the square root of X which is a perfect square, we need to find a number that when multiplied by itself equals X.

You: That’s great, but what about numbers that are not a perfect square?

Rahul: Great question 🙂

Numbers that are not a perfect square will have a real number (decimal) as their square root. So, we need a way to find the nearest approximate value for the square root (up to 6 decimal places for now). It’ll be something like: R.abcdef

Let’s say we need to find the square root of 13, which is not a perfect square. Let’s find R first.

Observe that the maximum perfect square less than 13 is 9 whose square root is 3. Since the square of 4 is 16, which is greater than 13, the square root of 13 has to be less than 4. So we can be sure that the square root of 13 as well will be something like 3.abcdef.

Now that we have the value of R(3), let’s find abcdef.

In order to find the decimal places, we can use Binary Search. We know that the square root will lie between (3, 4). We apply binary search in this range, to find the value whose square is equal to 13 (up to 6 decimal places). Here is a sample walkthrough of how we are applying binary search.

low = 3, high = 4, mid = 3.5, mid * mid = 12.25 < 13
low = 3.5, high = 4, mid = 3.75, mid * mid = 14.0625 > 13
low = 3.5, high = 3.75, mid = 3.625, mid * mid = 13.140625 > 13
low = 3.5, high = 3.625, mid = 3.5625, mid * mid = 12.69140625 < 13
.
.
.
low = 3.605550, high = 3.605551, mid = 3.605551, mid * mid = 12.9999997 == 13 (up to 6 decimal places)

Hence, the square root of 13 = 3.605551

Here is a snippet of this Algorithm:

private static double sqrt(double X) {
    for (int i = 1; i < X; ++i) {
        int p = i * i;
        if (p == X) {
            // perfect square
            return i;
        }
        if (p > X) {
            // found left part of decimal
            return sqrt(X, i - 1, i);
        }
    }
    return Double.NaN;
}


private static double sqrt(double X, double low, double high) {
    double mid = (low + high) / 2;
    double p = mid * mid;
    // uncomment below line to see how we reach the final answer
    // System.out.println(low + " " + high + " " + mid + " " + p);

    if (p == X || (Math.abs(X - p) < PRECISION)) {
        return mid;
    }
    if (p < X) {
        return sqrt(X, mid, high);
    }
    return sqrt(X, low, mid);
}

Conclusion

Today we learned how a simple problem of finding the square and square root of a number can be solved in different ways in Java.

Thanks for reading. May the code be with you 🙂

Exercise:

  • What will happen if a negative number is passed as the exponent parameter to the Math.pow function?

  • What will happen if a negative number is passed to the Math.sqrt function?

  • Can you think of improving the time complexity of the binary search algorithm we used above to find the square root of a number?

Hint: Can we apply binary search somewhere else as well? 😛