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?
Edit: 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.
For example the answer even provides how to round to nearest integer: just input 4*x
to the algorithm.
ceil(x) : Returns the smallest integer that is greater than or equal to x (i.e : rounds up the nearest integer).
How to calculate the ceiling value? The ceiling function is related to the floor function by the formula: ⌈x⌉=−⌊−x⌋.
In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With