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 snippet :
unsigned long int a;
double apower;
apower = log((double)a) / log((double)2);
I found that value of 'apower' is wrong at some large value of a, I do not know the value, as my code fails, after I submit it. Why is it so? Is there some casting issue?
Following is the entire snippet :
int count = 0;
unsigned long int a,b;
double apower,bpower;
apower = log((double)a) / log((double)2);
bpower = log((double)b) / log((double)2);
count = abs(apower - bpower);
printf("%d\n",count);
Values of a and b will always be power of 2. So apower and bpower must be have 00 in decimal places. That is why, value of count will be int (%d). I just want to know the behavior of Logarithm.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With