ilove_sundarKanya's blog

By ilove_sundarKanya, history, 7 weeks ago, In English

I’d like to share a tip that could save you time and frustration, especially in competitive programming: avoid using C++’s pow function when working with integers.

Recently, I spent nearly an hour debugging a lengthy piece of code, only to realize that the issue stemmed from using pow. Despite its convenience, pow can sometimes introduce unexpected precision errors when working with integer calculations. This can lead to incorrect results, especially in competitive programming where accuracy is key.

Instead, consider writing a custom power function or using iterative multiplication for integer exponentiation. This approach is often more reliable and can help you avoid subtle bugs related to precision issues in pow.

Hope this tip saves you time in the future!

Thank you!

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

»
7 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Could you elaborate on what kind of issues you can face ? I mean maybe a small example for me .Thanks

»
7 weeks ago, # |
  Vote: I like it +4 Vote: I do not like it

As a rule of thumb, If you have a problem where the inputs are integers, the outputs are integers and it is not explicitly said in the statement that you should do something deeply real-valued, 98% of the time you do not need any floating-point mess in your solution. Learn to cleverly use integer division, rational numbers, apply some rewriting rules such as $$$a / b < c / d \Longleftrightarrow ad \mathop{\mathrm{sign}}(bd) < bc \mathop{\mathrm{sign}}(bd)$$$, $$$x > f^{-1}(y) \Longleftrightarrow f(x) > y$$$ (for an increasing function $$$f$$$), etc. Most of geometry can be solved in integers as well if you store lines as $$$ax + by + c = 0$$$ and non-integer points as $$$(\frac{x}{c}, \frac{y}{c})$$$.