有什么方法来确定是否一个int是在Haskell一个完美的正方形? [英] What's the way to determine if an Int is a perfect square in Haskell?

查看:105
本文介绍了有什么方法来确定是否一个int是在Haskell一个完美的正方形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简单的函数

is_square :: Int -> Bool

如果一个Int N的确定完全平方(有一个整数x,使得X * X = N)。

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

当然,我可以只写像

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

但它看起来很可怕!也许有实现这样的predicate一种常见的简单的方法?

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

推荐答案

呵呵,今天我需要确定一个数是否为完美的多维数据集,类似的解决方案是非常缓慢的。

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

所以,我想出了一个pretty的聪明替代

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

这篇关于有什么方法来确定是否一个int是在Haskell一个完美的正方形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆