How to compute square roots without dependency on Float arithmetics?

You could use Newton’s method using only integer division:

module Newton exposing (sqrt)


sqrt : Int -> Maybe Int
sqrt n =
    if n < 0 then
        Nothing

    else
        Just (sqrtHelp n n)


sqrtHelp : Int -> Int -> Int
sqrtHelp n x =
    let
        nextX =
            (x + n // x) // 2
    in
    if abs (nextX - x) < 1 then
        nextX

    else if nextX == x + 1 then
        x

    else
        sqrtHelp n nextX
5 Likes