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). Hereigoes over the odd numbers andkis their sum. It stops when the sum is more thann. At this pointi == (2*x-1) + 2wherexis the square root, sox == floor(i/2).