How to find the sqrt(num)
Problem statement
Compute and return the square root of a non-negative integer number.
The decimal digits are shortened, and only the integer component of the result is returned because the return type is an integer.
Example 1
- Input:
num = 8 - Output:
2
Example 2
- Input:
num = 4 - Output:
2
Solution
We can use binary search to solve this problem.
The intuition behind the solution is that the square root of the number lies in the range [2, num / 2]. So, we can consider the range to be an array of numbers and search for the integer part of the square root of the number.
The steps of the algorithm are as follows:
-
Initialize
start=2andend=num/2. -
Until
start <= end, do the following:- Find the mid element using the formula
start + (end - start) / 2. - Find the square of the mid element, i.e.,
mid * midand store it in a variablemidSqr. - If the
midSqris greater thannum, it means the result lies in the left part of the array, i.e., fromstarttomid-1. - If the
midSqris lesser thannum, it means the result lies in the right part of the array, i.e., frommid+1toend. - If the
midSqris equal tonum, it means we have found the result.
- Find the mid element using the formula
-
When
end > start, the loop finishes, and theendwill be the result.
- Time Complexity:
O(log (num)) - Space Complexity:
O(1)
Look at the following illustration for a better understanding of the algorithm.
Code
import java.util.*;public class Main{private static int sqrt(int num){int start = 2, end = num / 2;while(start <= end){int mid = start + (end - start) / 2;long midSqr = (long) mid * mid;if(midSqr > num) end = mid - 1;else if(midSqr < num) start = mid + 1;else return mid;}return end;}public static void main( String args[] ) {Scanner scanner = new Scanner(System.in);int num = scanner.nextInt();System.out.printf("Sqrt(%s) = %s", num, sqrt(num));}}
Enter the input below