Fearless_cod's blog

By Fearless_cod, history, 2 years ago, In English

Hi reader. Coming straight to the point. The value of (1ll<<59) or 2^59 is 576460752303423488(say x).So if you do log2(x),the answer should come out to be 59.That's indeed the case. But here is the catch... .If you do log2(x-1) in C++ 14(not sure for other versions),it also gives 59 as output..(but actual answer is 58), which is wrong and that caused me a fst in recent Div 3 problem F.

So, can anyone explain why is this happening and how to avoid these types of things. Thanks for spending your time in reading this blog.

  • Vote: I like it
  • +4
  • Vote: I do not like it

| Write comment?
»
2 years ago, # |
  Vote: I like it +13 Vote: I do not like it
  • »
    »
    2 years ago, # ^ |
    Rev. 2   Vote: I like it +2 Vote: I do not like it

    Not only log2(). You should also be careful with pow(), sqrt(), and any other inbuilt functions that operate on integers $$$\ge 2^{31}$$$.

»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Thanks bro. Got it.

»
2 years ago, # |
  Vote: I like it +7 Vote: I do not like it

I use log2((long double)x).It even works for integers >2^31.

»
2 years ago, # |
  Vote: I like it +11 Vote: I do not like it

Use __lg(x) for floored log2.

»
2 years ago, # |
Rev. 11   Vote: I like it +6 Vote: I do not like it

I use

This

I got to know about this when I was solving this question Here is my submission without using the above code which gave me a WA and here is my submission with the above code give gave me a AC. Hope was helpful