How can you easily calculate the square root of an unsigned long long in C?

前端 未结 5 1437
终归单人心
终归单人心 2020-12-19 08:56

I was looking at another question (here) where someone was looking for a way to get the square root of a 64 bit integer in x86 assembly.

This turns out to be very si

5条回答
  •  北海茫月
    2020-12-19 09:19

    If you only want to calculate sqrt for integers, using divide and conquer should find the result in max 32 iterations:

    uint64_t mysqrt (uint64_t a)
    {
      uint64_t min=0;
      //uint64_t max=1<<32;
      uint64_t max=((uint64_t) 1) << 32; //chux' bugfix
      while(1)
        {
           if (max <= 1 + min)
             return min;           
    
           uint64_t sqt = min + (max - min)/2;
           uint64_t sq = sqt*sqt;
    
           if (sq == a) 
             return sqt;
    
           if (sq > a)
             max = sqt;
           else
             min = sqt;
        }
    

    Debugging is left as exercise for the reader.

提交回复
热议问题