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 ?
Step 1: First pair the digits starting from right to left. Step 2: Match the unit digit of number from the chart and determine the possible values of the square root of the unit digit. Step 3: Let us consider the group of the first three digits. Let it be "n".
We can use four methods to find the square root of numbers and those methods are as follows: Repeated Subtraction Method of Square Root. Square Root by Prime Factorization Method. Square Root by Estimation Method.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With