Print Square Root of A Number in Java

Confronting with numbers is the first thing each one of us has learned in school. However, as we step up high more and more difficult questions based on the same fundamentals seem to appear in our way. It’s the same with programming, using the same fundamentals to find solutions for multiple complex problems. Now the cool thing is, you can be creative in your way eventually coming up with a unique solution. And if you’re able to do this, then you’ve clearly understood how to use programming for others and your good. But keeping that aside, we’ve talked about numbers before. So what if we find the square root of numbers, seems too easy right!. Well, So let’s quickly find out how to Print the Square Root of A Number in Java.

With the help of this program, you will be able to find the root square of integers. Practicing these types of questions also helps to get an upper edge in Competitive Programming.

 

What’s The Approach?

 

  • We will start finding the square of numbers greater than 1.

 

  • With an increment of 1 at each iteration, this instruction will keep going till we get the square of the number less than or equal to the input number  x
  • How to type square root √

 

  • We’ll run a while loop with the condition as i*i < = x, here i*i is the square we want to find.

 

  • Once the above condition is satisfied we’ll return i-1 as the square root of input number x

 

Also Read: Print Palindrome Numbers in Given Range using Java

 

Java Program To Print Square Root of A Number

 

Input:

x = 11

 

Output:

3

 

// A Java program to find Square Root of A Number

class TechDecodeTutorials {
    
    // Returns floor of square root of x
    static int floorSqrt(int x)
    {
        // Base cases
        if (x == 0 || x == 1)
            return x;

        // Staring from 1, try all numbers until
        // i*i is greater than or equal to x.
        int i = 1, result = 1;
        
        while (result <= x) {
            i++;
            result = i * i;
        }
        return i - 1;
    }

    // Driver program
    public static void main(String[] args)
    {
        int x = 11;
        System.out.print(floorSqrt(x));
    }
}


 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published.