CC-14 : Find Square root of a number.
Description:
Given an input number find its square root. If the input number is not a perfect square, then its square root will be a decimal number. In case of decimal square root, just return the integer part of square root.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Num=144 | Square root of 144 is 12 |
| Num=16 | Square root of 16 is 4 |
| Num=12 | Square root of 12 is 3 |
Pseudocode:
findSqrt(num):
| Integer named num is received as input parameter. |
| Set integer variable firstNum to zero, we will use this variable to store the first number above which we will search for square root of num. |
| Set integer variable lastNum to nums, we will use this variable to store the last number below which we will search for square root of num. |
| Set integer variable sqrt to 1. |
| While (firstNum <= lastNum) do the following steps:
Set integer variable mid to (lastNum-firstNum)/2.
Set integer variable midNum to (firstNum)to get mid number of current range.
If (midNum*midNum<=nums ):
Set sqrt=midNum.
Set firstNum=midNum+1.
Else if (midNum*midNum > nums ) then:
lastNum=midNum-1.
|
| Return sqrt as it contains the square root of num. |
Code:
public int findSqrt(int num){
int firstNum=1;
int lastNum=num;
int sqrt=1;
while (firstNum <= lastNum) {
int mid=(lastNum-firstNum)/2;
int midNum=firstNum+mid;
if (midNum*midNum<=num) {
sqrt=midNum;
firstNum=midNum+1;
} else { if (midNum*midNum > num) {
lastNum=midNum-1;
}
}
}
return sqrt;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |