Haskell integer square root function

Integer the square root of a natural number n is the largest integer whose square is less than or equal to n. (For example, the integer square root of 7 is 2, and the number of 9 is 3).

Here is my attempt:

intSquareRoot :: Int -> Int
intSquareRoot n
    | n*n > n   = intSquareRoot (n - 1) 
    | n*n <= n  = n

I assume that it does not work because n decreases along with recursion as needed, but because of this, Haskell you cannot use variables to keep the original n.

+4
source share
3 answers

... but because of this Haskell, you cannot use variables to keep the original n.

I do not know what made you say this. Here you can implement it:

intSquareRoot :: Int -> Int
intSquareRoot n = aux n
  where
    aux x
      | x*x > n = aux (x - 1)
      | otherwise = x

, , . Haskell wiki:

(^!) :: Num a => a -> Int -> a
(^!) x n = x^n

squareRoot :: Integer -> Integer
squareRoot 0 = 0
squareRoot 1 = 1
squareRoot n =
   let twopows = iterate (^!2) 2
       (lowerRoot, lowerN) =
          last $ takeWhile ((n>=) . snd) $ zip (1:twopows) twopows
       newtonStep x = div (x + div n x) 2
       iters = iterate newtonStep (squareRoot (div n lowerN) * lowerRoot)
       isRoot r  =  r^!2 <= n && n < (r+1)^!2
  in  head $ dropWhile (not . isRoot) iters
+6

, ....

intSquareRoot :: Int -> Int
intSquareRoot n = try n where
  try i   | i*i > n   = try (i - 1) 
          | i*i <= n  = i

ghci> intSquareRoot 16
4
ghci> intSquareRoot 17
4
+5

, user2989737, n . , O (n). 0 , O (sqrt n):

intSquareRoot :: Int -> Int
intSquareRoot n = try 0 where
  try i   | i*i <= n    = try (i + 1) 
          | True        = i - 1

( ):

squareRoot :: Integral t => t -> t
squareRoot n 
   | n > 0    = babylon n
   | n == 0   = 0
   | n < 0    = error "Negative input"
   where
   babylon a   | a > b  = babylon b
               | True   = a
      where b  = quot (a + quot n a) 2

, ( GNU), . , n.

To do this, I generalized it to any type of Integral, checked for negative input and checked n == 0 to avoid dividing by 0.

+1
source

All Articles