整数ceil(sqrt(x)) [英] Integer ceil(sqrt(x))

查看:432
本文介绍了整数ceil(sqrt(x))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

答案提供了以下用于计算楼层的代码(sqrt(x))只使用整数。是否可以使用/修改它来返回 ceil(sqrt(x))?或者,计算这样的价值的首选方法是什么?

The answer gives the following code for computing floor(sqrt(x)) using just integers. Is it possible to use/modify it to return ceil(sqrt(x)) instead? Alternatively, what is the preferred way to calculate such value?

编辑:谢谢大家到目前为止我道歉,我应该让它更明确:我希望那里使用 floor(sqrt(x)),可能加一个更自然的方式。 floor 版本使用Newton的方法从上面接近root,我认为可能从下面接近它或类似的就可以了。

Thank you all so far and I apologise, I should have make it more explicit: I was hoping there is more "natural" way of doing this that using floor(sqrt(x)), possibly plus one. The floor version uses Newton's method to approach the root from above, I thought that maybe approaching it from below or similar would do the trick.

例如,答案甚至提供了如何舍入到最接近的整数:只需输入 4 * x 算法。

For example the answer even provides how to round to nearest integer: just input 4*x to the algorithm.

推荐答案

如果 x 是一个精确的正方形,则平方根的上限和下限是相等的;否则,天花板比平方根多一个。所以你可以使用(在Python中),

If x is an exact square, the ceiling and the floor of the square root are equal; otherwise, the ceiling is one more than the square root. So you could use (in Python),

result = floorsqrt(x)
if result * result != x:
    result += 1

修改链接的代码并不是一个好主意,因为该代码使用Newton-Raphson方法计算平方根的一些属性。关于该方法已经开发了很多理论,并且代码使用了该理论。我展示的代码不像修改链接代码那样整洁,但它比更改代码更安全,也可能更快。

Modifying the code you linked to is not a good idea, since that code uses some properties of the Newton-Raphson method of calculating the square root. Much theory has been developed about that method, and the code uses that theory. The code I show is not as neat as modifying your linked code but it is safer and probably quicker than making a change in the code.

这篇关于整数ceil(sqrt(x))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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