Fastest way to determine if an integer's square root is an integer

前端 未结 30 2264
心在旅途
心在旅途 2020-11-22 02:17

I\'m looking for the fastest way to determine if a long value is a perfect square (i.e. its square root is another integer):

  1. I\'ve done it the ea
30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:43

    You should get rid of the 2-power part of N right from the start.

    2nd Edit The magical expression for m below should be

    m = N - (N & (N-1));
    

    and not as written

    End of 2nd edit

    m = N & (N-1); // the lawest bit of N
    N /= m;
    byte = N & 0x0F;
    if ((m % 2) || (byte !=1 && byte !=9))
      return false;
    

    1st Edit:

    Minor improvement:

    m = N & (N-1); // the lawest bit of N
    N /= m;
    if ((m % 2) || (N & 0x07 != 1))
      return false;
    

    End of 1st edit

    Now continue as usual. This way, by the time you get to the floating point part, you already got rid of all the numbers whose 2-power part is odd (about half), and then you only consider 1/8 of whats left. I.e. you run the floating point part on 6% of the numbers.

提交回复
热议问题