Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer 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?

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.

like image 946
minmax Avatar asked Jul 08 '18 16:07

minmax


People also ask

What does ceil X function do?

ceil(x) : Returns the smallest integer that is greater than or equal to x (i.e : rounds up the nearest integer).

How do I find the ceil of a number?

How to calculate the ceiling value? The ceiling function is related to the floor function by the formula: ⌈x⌉=−⌊−x⌋.

What is ceil function in C?

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).


1 Answers

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.

like image 155
Rory Daulton Avatar answered Dec 30 '22 00:12

Rory Daulton