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

前端 未结 30 2254
心在旅途
心在旅途 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:42

    It ought to be possible to pack the 'cannot be a perfect square if the last X digits are N' much more efficiently than that! I'll use java 32 bit ints, and produce enough data to check the last 16 bits of the number - that's 2048 hexadecimal int values.

    ...

    Ok. Either I have run into some number theory that is a little beyond me, or there is a bug in my code. In any case, here is the code:

    public static void main(String[] args) {
        final int BITS = 16;
    
        BitSet foo = new BitSet();
    
        for(int i = 0; i< (1<

    and here are the results:

    (ed: elided for poor performance in prettify.js; view revision history to see.)

提交回复
热议问题