【发布时间】:2018-06-07 00:13:33
【问题描述】:
我解决了以下练习,但我不喜欢该解决方案:
使用递归编写函数 isPerfectSquare,以判断是否存在 Int 是一个完美的正方形 isPerfectSquare 1 -> 应该返回 True
isPerfectSquare 3 -> 应该返回 False
num+1 部分用于isPerfectSquare 0 and isPerfectSquare 1 的情况,这是我一点都不喜欢的部分之一,这是我的解决方案:
perfectSquare 0 1 = [0] ++ perfectSquare 1 3
perfectSquare current diff = [current] ++ perfectSquare (current + diff) (diff + 2)
isPerfectSquare num = any (==num) (take (num+1) (perfectSquare 0 1))
对于这个问题有什么更优雅的解决方案?当然我们不能使用 sqrt,也不能使用浮点运算。
【问题讨论】:
-
平方是单调运算,所以你可以对它的逆进行二分搜索,这会比你这里的要快得多(而且很自然地递归)
-
另外,为了激发你的胃口,
perfectSquare使用的模式实际上被称为 corecursive (但对于一个类而言,它会被视为递归当然) -
@luqui 谢谢,我刚刚在下面写了评论