Given 2^n, find n using logarithm

前端 未结 3 2041
醉话见心
醉话见心 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.

提交回复
热议问题