Search code examples
algorithmhaskellsqrt

What's the way to determine if an Int is a perfect square in Haskell?


I need a simple function

is_square :: Int -> Bool

which determines if an Int N a perfect square (is there an integer x such that x*x = N).

Of course I can just write something like

is_square n = sq * sq == n
    where sq = floor $ sqrt $ (fromIntegral n::Double)

but it looks terrible! Maybe there is a common simple way to implement such a predicate?


Solution

  • Oh, today I needed to determine if a number is perfect cube, and similar solution was VERY slow.

    So, I came up with a pretty clever alternative

    cubes = map (\x -> x*x*x) [1..]
    is_cube n = n == (head $ dropWhile (<n) cubes)
    

    Very simple. I think, I need to use a tree for faster lookups, but now I'll try this solution, maybe it will be fast enough for my task. If not, I'll edit the answer with proper datastructure