Sunday 5 June 2016

Haskell: Find integer square root of a number

The integer square root of a positive integer n is the largest integer whose square is less than or equal to n. The integer square roots of 24 and 25 are 4 and 5, respectively.


Sample.hs
getSquareRoot :: Integer -> Integer
getSquareRoot num
    | (num <= 0) = error "Not Applicable"
    | otherwise = getSquareRoot' 1 2 num


getSquareRoot' :: Integer -> Integer -> Integer -> Integer
getSquareRoot' x y num = 
    if(betweenSquares x y num) 
        then 
            if (num == square y) 
                then 
                    y 
                else 
                    x 
        else 
            getSquareRoot' (inc x) (inc y) num

square :: Integer -> Integer
square num = num * num

-- if x*x <= num <= y*y, then return True, else False
betweenSquares :: Integer -> Integer -> Integer -> Bool
betweenSquares x y num = ((square x) <= num) && ((num <= square y))

inc :: Integer -> Integer
inc x = x + 1

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getSquareRoot 10
3
*Main> getSquareRoot 16
4
*Main> getSquareRoot 25
5
*Main> getSquareRoot 24
4



Previous                                                 Next                                                 Home

No comments:

Post a Comment