How to write a Golang program to find the square root of a number is a common Go programming exercise. Go program for square root is also a popular question during college semester exams and various programming tests. If you are familiar with Go API then writing a Go program that can find the square root of a number using math library is not difficult. You just need to pass a double value and it returns a double which is the square root of the number you passed.
The square root is just the opposite of the square. The square root of a number, n, is the number that gives n when multiplied by itself. Mathematically, the square root of a number is given as,
Square Root of n = √n
Now that you know what square and square root of a number are, let’s see different ways to calculate them in Golang.
GoLang: Write a go function, find_square() that accepts an integer number, n and returns the square of n.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package main import "fmt" func main() { var result float64; result=find_square(16) fmt.Println(result) } func find_square(number float64) float64{ var sr float64 = number / 2 var temp float64; for{ temp = sr sr = (temp + (number / temp)) / 2 if(temp - sr) == 0{ break; } } return sr } |
Output:
1 2 3 | 4 |