2

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!

neubert
  • 142

2 Answers2

6

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

2

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.

colormegone
  • 11,002