5 ms·
If that function is really supposed to return the square of a number, you took a wrong turn somewhere. Because it says the square of 16 is 56. Now here's a mo
by bartl 10y ago
If that function is really supposed to return the square of a number, you took a wrong turn somewhere. Because it says the square of 16 is 56.
Now here's a more efficient algorithm which does produce the currect result:
int square(int num) {
int a = 0;
for (int x = 1, n = num; x <= num; x+=x, n+=n) {
if( num & x) {
a += n;
}
}
return a;
}
It would be nice if this site allowed us to run/step through the code, to see exactly what it is doing.
- rzimmerman 10y agoOh, sorry, I never bothered to change the function name. It's just an interesting loop.