Just an exercise:
func mySqrt(_ x: Int) -> Int {
if x<2 { return x }
var y = x
var z = (y + (x/y)) / 2
while Double(abs(y - z)) >= 0.00001 {
y = z
z = (y + (x/y)) / 2
}
return z
}
I went through many answers in StackOverflow but couldn't get a better solution, e.g.
Best way to calculate the square root of any number in ios , Objective C and Swift
Finding square root without using sqrt function?
Take input x = 4 or any perfect square, it works fine. Now, take something like x = 8, It Time out.
Please help me out, what I am doing wrong.