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: ( x 2 + 1 ) 2 ≥ x (\frac{x}{2} + 1)^2≥ x \\ (2x+1)2x
    So, the maximum value of the root should not exceed x 2 \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.The time complexity of this code is O(n), and the space complexity of the code is O(n) too. In terms of algorithm complexity, this code is very efficient and relatively low memory consumption.

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:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值