Rounding up to Nearest Square

Rounding up to Nearest Square
$\begingroup$

Say I have x and want to round it up to the nearest square. How might I do that in a constant time manner?

ie.

$2^2$ is 4 and $3^2$ is 9. So I want a formula whereby f(x) = 9 when x is 5, 6, 7 or 8. What it does when x = 4 or 9 doesn't really matter.

I could write a function to do this easily enough. ie.

while (sqrt(x) is not int) {
  x++;
}

But I'd rather not do a brute force approach. Any ideas?

Thanks!

$\endgroup$

2 Answers

$\begingroup$

You can take the ceiling of $\sqrt{x}$ and square it.

$\endgroup$
$\begingroup$

I don't know if this is quite what you're looking for, but you can use the fact that $ \ (n+1)^2 \ = \ n^2 \ + \ (2n + 1) \ $ . Once you reach a perfect square $ \ n^2 \ $ , the next $ \ 2n \ $ integers would be the ones that get "rounded-up". This is at least reduces the process to a test for perfect-square and a counting loop.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.