I've been told this code snippet is equivalent to (int)sqrt(n)
int s(int n) {
for (int i = 1, k = 0; n > 0; i += 2) {
if (k + i > n)
return i / 2;
k += i;
}
return 0;
}
And it seem to work, yet I don't understand how it works ?
It uses the fact that
x^2 = 1 + 3 + 5 + ... + (2*x-1)
. Herei
goes over the odd numbers andk
is their sum. It stops when the sum is more thann
. At this pointi == (2*x-1) + 2
wherex
is the square root, sox == floor(i/2)
.