-3

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.

Renuka Pandey
  • 1,730
  • 2
  • 15
  • 27
  • 1
    Why should a sqrt function return an integer, what is the expected result for `mySqrt(8)` for instance? – Joakim Danielson Nov 10 '22 at 15:44
  • 1
    Note that square root is an expensive operation. The built-in function takes advantage of hardware acceleration, and is likely **thousands** of times faster than doing it manually. I'm assuming this is an exercise? – Duncan C Nov 10 '22 at 16:13
  • @DuncanC Yes this is just exercise – Renuka Pandey Nov 10 '22 at 16:14
  • 1
    It would be interesting to benchmark the manual vs. built-in version. I bet you could calculate >1000 square roots with the built-in faster than you could calculate a single non-perfect-square value. – Duncan C Nov 10 '22 at 16:25
  • @DuncanC True that :) – Renuka Pandey Nov 10 '22 at 16:26

1 Answers1

1

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.

HangarRash
  • 7,314
  • 5
  • 5
  • 32