So here's the 'C' implementation of the 'Threshold Whole Square Method' I talked about (here). This one is only for 'long' data-type, but I've written a generic one that can deal with float types too, but I'll post that one later.
Code:
long lsqr(long n) {
if (n > 1)
{
long twoBase = 1, i;
for (i = 1; twoBase <= n; i++)
{
twoBase <<= 1;
}
twoBase >>= 1;
long k = (long)(n - twoBase);
long sqrN = (long)(twoBase << i - 2);
return (k == 0 ? sqrN : sqrN + lsqr(k) + ((k * twoBase) << 1));
}
else
return n;
}
Basically, the variable twoBase is the nearest threshold which is a power of 2, so that it can be used as 'n' in the formula mentioned in that other post. This is done as the whole square of this number can be calculated very cheaply by a simple left shift operation. After that, the difference between the given number and this threshold is calculated to determine 'k', i.e. the offset. Then a simple application of the formula gives the result. The advantage of this method is that the we need to effectively calculate the whole-square of just a very small number (the offset 'k'), instead of the conventional calculation of the entire number 'n'. This make this method marginally faster than the compiler's method, but this one can only be used for 'long' data types and should be used carefully.
No comments:
Post a Comment