algorithm - 确定 Int 是否为 Haskell 中的完美正方形的方法是什么?

标签 algorithm haskell sqrt

我需要一个简单的函数

is_square :: Int -> Bool

它确定 Int N 是否为完全平方(是否存在满足 x*x = N 的整数 x)。

当然我也可以这样写

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

但看起来很糟糕!也许有一种通用的简单方法来实现这样的谓词?

最佳答案

这样想,如果您有一个正整数 n,那么您基本上是在从 1 到 n 的数字范围内进行二进制搜索以找到第一个数字 n' 其中 n' * n' = n

我不懂 Haskell,但是这个 F# 应该很容易转换:

let is_perfect_square n =
    let rec binary_search low high =
        let mid = (high + low) / 2
        let midSquare = mid * mid

        if low > high then false
        elif n = midSquare then true
        else if n < midSquare then binary_search low (mid - 1)
        else binary_search (mid + 1) high

    binary_search 1 n

保证为 O(log n)。易于修改完美的立方体和更高的功率。

关于algorithm - 确定 Int 是否为 Haskell 中的完美正方形的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2807686/

相关文章:

algorithm - 什么是最好的矩阵乘法算法?

构建多类(相对于二元)分类器的算法

c++ - 检查 "Whether for a given directed graph there is only one way to sort the graph using topological sort or not"的算法优化

haskell - 将递归函数重写为管道函数组合

perl - 如何设置Raku的sqrt的精确度?

Java替换字符串中的一个字符

list - 在列表列表中追加列表 - Haskell

haskell - 我如何告诉 Cabal 使用哪个依赖项?

javascript - 检查数字字符串是否包含十进制?

c++:static_cast<int> std::sqrt(x) 是否总是为平方的正整数给出准确的结果?