Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate SquareRoot of Integer without using inbuilt function in Swift Language? I tried below code & searched but didn't get better solution

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading