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.
The problem is you are trying to use integers for all of the calculations.
The square root of 8 is not an integer. You need to use Double
for all of your variables (except optionally leave parameter as an Int
). The return value needs to be a Double
if you want a meaningful answer.
Here's your code using Double
where needed:
func mySqrt(_ x: Int) -> Double {
if x < 2 { return Double(x) }
var y = Double(x)
var z = (y + (Double(x)/y)) / 2
while (abs(y - z)) >= 0.00001 {
y = z
z = (y + (Double(x)/y)) / 2
}
return z
}
print(mySqrt(8))
This gives the correct result.