Solution for the Square Root of x Using the Go Language

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:

  1. 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.
  2. Determine the range of values to be calculated. It’s not hard to find that: (x2+1)2x (\frac{x}{2} + 1)^2≥ x \\ (2x​+1)2≥x
    So, the maximum value of the root should not exceed x2\frac{x}{2}2x​.
  3. 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:
Solution for the Square Root of x Using the Go Language
Solution for the Square Root of x Using the Go Language

上一篇:CSS清除浮动方法二


下一篇:Latin Square(二分图匹配)