Skip to content

Instantly share code, notes, and snippets.

@ant358
Created November 26, 2023 19:13
Show Gist options
  • Save ant358/af4299da5ab12b1ddb2393804c172a46 to your computer and use it in GitHub Desktop.
Save ant358/af4299da5ab12b1ddb2393804c172a46 to your computer and use it in GitHub Desktop.
Exercise: Loops and Functions. Solution
import (
"fmt"
"math"
)
var j int = 10
func Sqrt(x float64) float64 {
return math.Sqrt(x)
}
func main() {
z := 10.0
x := 17002.0
fmt.Printf("x is %v\n", x)
fmt.Printf("The square root solution from math = %v\n", Sqrt(x))
fmt.Printf("The starting value of z = %v\n", z)
for i := 0; i < j; i++ {
z -= (z*z - x) / (2 * z)
if z == Sqrt(x) {
fmt.Printf("It took %v iterations to find z\n", i)
fmt.Printf("Final value of z = %v, x was %v ", z, x)
break
}
}
fmt.Printf("Z not found in %v iterations\n", j)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment