Weird way of calculating square root

119 views Asked by At

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 ?

1

There are 1 answers

0
interjay On BEST ANSWER

It uses the fact that x^2 = 1 + 3 + 5 + ... + (2*x-1). Here i goes over the odd numbers and k is their sum. It stops when the sum is more than n. At this point i == (2*x-1) + 2 where x is the square root, so x == floor(i/2).