Skip to content

Instantly share code, notes, and snippets.

@akhilcb
Created July 9, 2017 02:59
Show Gist options
  • Save akhilcb/2d3f1a026e36d54dfe2793074dd91811 to your computer and use it in GitHub Desktop.
Save akhilcb/2d3f1a026e36d54dfe2793074dd91811 to your computer and use it in GitHub Desktop.
Finding Squareroot of a number without using any maths function(Efficient algorithm)
func squareroot(number: Double) -> Double {
if number <= 0 {
return 0
}
var x = number / 3
var y = number / x
let maxDiff: Double = 0.0001
while abs(y - x) > maxDiff {
x = (x + y) / 2
y = number / x
}
return x
}
let squreroot = squareroot(number: 9000000)
print("squreroot = ", squreroot)
//Output:
//squreroot = 3000.00000000004
// while loop is executed only 14 times for a value of 9000000.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment