my problem is creating a sqrt function for integer via Scala
f.e.: sqrt ( 26 ) = 6 , s² >= n sqrt (0) = 0, sqrt (1) = 1, sqrt (2) = 2, sqrt (3) = 2, sqrt (4) = 2, sqrt (5) to sqrt (9) = 3 ....
here is my code i came up with:
def sqrt (n: Int): Int = {
def sq (a: Int, n: Int): Int = {
val b = (a + n) / 2
val c = (b + n / b) / 2
if (b * b == n) b
else if (b * b < n) b + 1
else c
}
if (n == 0 || n == 1) n else sq (0 , n)
}
however it doesn't work with all the numbers n >= 0. f.e.: for 6 its 2, how do i tweak my formula?