Celeb Glow
news | April 19, 2026

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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