Data Structure & Algorithms
DSA
Introduction to problem solving
Square Root of Number

# Square root of a number

## Problem Description

Given a number A. Return square root of the number if it is perfect square otherwise return -1.

Note : A number is a perfect square if its square root is an integer.

### Problem Constraints

``1 <= A <= 10^8``

### Input Format

``First and the only argument is an integer A.``

### Output Format

``Return an integer which is the square root of A if A is perfect square otherwise return -1.``

### Example Input

``````Input 1:
A = 4

Input 2:
A = 1001``````

### Example Output

``````Output 1:
2

Output 2:
-1``````

### Example Explanation

``````Explanation 1:
sqrt(4) = 2

Explanation 2:
1001 is not a perfect square.``````

### Output

Java
``````public class Solution {
public int sqrt(int A) {
long start = 1, end = A, ans = -1;
while (start <= end) {
long mid = (start + end) / 2;
if (mid * mid == A) return (int)mid;
if (mid * mid < A) {
start = mid + 1;
ans = mid;
} else {
end = mid - 1;
}
}
return (int)ans;
}
}``````
Python
``````class Solution:
def sqrt(self, A):
start, end, ans = 1, A, -1
while start <= end:
mid = (start + end) // 2
if mid * mid == A:
return mid
if mid * mid < A:
start = mid + 1
ans = mid
else:
end = mid - 1
return ans``````
JavaScript
``````function sqrt(A) {
let start = 1, end = A, ans = -1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (mid * mid === A) return mid;
if (mid * mid < A) {
start = mid + 1;
ans = mid;
} else {
end = mid - 1;
}
}
return ans;
}``````