Implement int sqrt(int x) function.
Calculate and return the square root of x, where x is a non-negative integer.
Since the return type is an integer, the result retains only the integer part, and the decimal part is dropped.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Instructions: The square root of 8 is 2.82842…
Since the return type is an integer, the decimal part will be omitted.
Next, I will explain my solution to this problem:
- Determine the data type. Since the problem requires that the return type be an integer, the decimal part will be omitted, so I assign all values computed in the function to the integer type.
- Determine the range of values to be calculated. It’s not hard to find that: (2x+1)2≥x
So, the maximum value of the root should not exceed 2x. - We can consider a critical case: when the square of the value of the root is just above or equal to the value of x, the value of that root is returned.
Here is my code:
package main
import (
"fmt"
)
func main() {
var x int
fmt.Scan(&x)
var sqrt int
sqrt=mySqrt(x)
fmt.Println("Input:",x," Output:",sqrt)
}
func mySqrt(x int) int {
if(x<1){
return x
}
start:=0
end:=x/2+1
var answer int
for start=0;start<=end;start++ {
if start*start==x {
answer=start
}else if start*start>x{
answer=start-1
break //When start is greater than x, assign the value of start -1 to the answer
}
}
return answer
}
Out put: