Given 2^n, find n using logarithm

前端 未结 3 2038
醉话见心
醉话见心 2021-01-21 05:53

Given a integer(2^n) which is power of 2, I want to find out n, the index value using logarithm. The formula to find index is : log(number) / log(2). Following is the code snipp

相关标签:
3条回答
  • 2021-01-21 06:04

    I am only answering half of your question, because it is not necessary to use logs to solve this. An easy way is to use this:

    unsigned long long a = 0x8000000000000000ULL;
    int n = 0;
    while (a >>= 1) n++;
    printf("%d\n", n);
    

    Output:

    63
    

    Converting to logs and divding may cause loss of significance, in which case you should use round. You use the word "submit", so it was an online challenge that failed? What exactly did you print? (in this case) 63.000000? That would be got from the default format of %f.

    0 讨论(0)
  • 2021-01-21 06:14

    When using double math, the log result or quotient may not be exactly the mathematical result but 1 (or 2) next representable double away.

    Calculating log() only returns an exact mathematical result for log(0), all other mathematical results are irrational. All double are rational.

    This may result in an answer like 29.999999..., which saved as an int is 29.

    Recommend using integer math instead


    int mylog2(unsigned long x) {
      int y = 0;
      #if (ULONG_MAX>>16 > 1lu<<16)
        if (x >= 1lu<<32) { x >>= 32; y += 32;
      #endif
      if (x >= 1lu<<16) { x >>= 16; y += 16; }
      if (x >= 1lu<<8) { x >>= 8; y += 8; }
      if (x >= 1lu<<4) { x >>= 4; y += 4; }
      if (x >= 1lu<<2) { x >>= 2; y += 2; }
      if (x >= 1lu<<1) { x >>= 1; y += 1; }
      return y;
    }
    
    0 讨论(0)
  • 2021-01-21 06:24

    Why not take advantage of the fact that the log2 is stored in the exponent field of a double? :)

    unsigned long long a = 0x8000000000000000ULL;
    union {
      double d;
      unsigned long long l;
    } u;
    u.d = a;
    int apower = (u.l >> 52) - 1023;
    printf("%d\n", apower);
    

    Output:

    63
    

    This assumes that unsigned long longs and doubles are 64 bit and that the input is > 0.

    0 讨论(0)
提交回复
热议问题