Haskell中的整数平方根函数

编程入门 行业动态 更新时间:2024-10-27 08:35:59
本文介绍了Haskell中的整数平方根函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

正整数n的整数平方根是平方为的最大整数 小于或等于n. (例如7的整数平方根是2,而9的整数平方根是3).

The integer square root of a positive integer n is the largest integer whose square is less than or equal to n. (E.g. the integer square root of 7 is 2, and that of 9 is 3).

这是我的尝试:

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

我猜测它不起作用,因为n随需要递归而减少,但是由于这是Haskell,您不能使用变量来保留原始n.

I'm guessing its not working because n decreases along with the recursion as required, but due to this being Haskell you can't use variables to keep the original n.

推荐答案

...但是由于这是Haskell,您不能使用变量来保留原始n.

... but due to this being Haskell you cant use variables to keep the original n.

我不知道是什么让你这么说.这是实现它的方法:

I don't know what makes you say that. Here's how you could implement it:

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

这足够好玩,但是它不是一个非常有效的实现.可以在 Haskell的Wiki 中找到一个更好的版本:

This is good enough to play around, but it's not a very efficient implementation. A better one can be found on Haskell's 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

更多推荐

Haskell中的整数平方根函数

本文发布于:2023-11-29 23:42:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:平方根   整数   函数   Haskell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!