Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


Oh, sorry, I never bothered to change the function name. It's just an interesting loop.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: