BINTREE april challenge..Can anyone tell me what's wrong with this approach??

#include
#include
#include<math.h>
using namespace std;
int main()
{
unsigned long long int i,j,pos1,pos2,num1,num2,cases;
cin>>cases;
while(cases–)
{
cin>>i>>j;
pos1 = log(i)/log(2) + 1;
pos2 = log(j)/log(2) + 1;
num1 = pos1;
num2 = pos2;
if(pos1>pos2)
{
while(pos1!=pos2)
{
i = i/2;
pos1–;
}
}
else if(pos2>pos1)
{
while(pos2!=pos1)
{
j = j/2;
pos2–;
}
}
if(i==j)
cout<<(num1+num2-2pos1)<<endl;
else
{
while(i!=j)
{
i=i/2;
j=j/2;
pos1–;
}
cout<<(num1+num2-2
pos1)<<endl;
}
}
return 0;
}

I also tried the same but got wrong ans. I can’t find the reason of not working. Maybe some case was missing.

Using floating point operations expecting them to have accuracy for integers is typically a bad idea. Due to rounding errors, for some powers of 2, n=pow(2,m), the expression log(n)/log(2) will return a floating point number that is slightly smaller than m. Since you are then casting to int, this will become m-1 instead of the value you were expecting.

For a simple and correct implementation check out my solution.

1 Like

@pedrosorio thanks 4 pointing that mistake…i modified my code nd got AC… i will try not to do that silly mistake in future contests… thank you :slight_smile: