# how to get square root of a number in java ?

159 views
How to get square root of a number in java ?

by (3.7k points)

The given an integer x, find square root of it. If x is not a perfect square, then it returns floor(√x).

To find a floor of square root to try all numbers starting from 1. For every tried number i, if i*i is smaller than x, then increment i. We stop when i*i becomes more than or equal to x.

See the following running code to find square root:-

//Time Complexity O(squareroot N)
public static int getSqt(int num) {
if(num ==0 || num==1)
return 1;

int i=1;
while(i*i <= num) {
i++;
}
return i-1;
}

by (2.8k points)
To find square root of given number by using recursion. See the bellow code to find square root using recursion:-

//Time Complexity O(squareroot N)

public static int getSqtRec(int num, int i) {

if(num ==0 || num==1)

return 1;

if(i*i > num) {

return i-1;

}

i=i+1;

return getSqtRec(num, i);

}
by (4.4k points)
To get square root of a given number in best way. The time complexity is O(logX). See the bellow code for finding the square root:-

//Time Complexity O(logX)

public static int getSqrtWithBestApproarch(int num) {

//Base Cases

if(num == 0 || num ==1) {

return num;

}

int start=1,end=num, result = 0;

while(start <= end) {

int mid = (start+end)/2;

//Perfect square root

if(mid * mid == num) {

return mid;

}

//Find floar value of square root

if(mid * mid < num) {

start = mid+1;

result = mid;

}else {//If mid*mid is greater than num

end = mid-1;

}

}

return result;

}