Square root of a number

Solution in Go

Using Binary Search

func mySqrt(x int) int {
    // Handle cases for 0 and 1
    if x <= 1 {
        return x
    }

    start := 1
    end := x / 2

    for start <= end {
        middle := start + ((end - start) / 2)

        v := middle * middle

        if v == x {
            return middle
        } else if v > x {
            end = middle - 1
        } else {
            start = middle + 1
        }
    }

    return end
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.