Detecting a unsigned integer overflow in a c function

The expression n /= 2; should never overflow, so I’m not worried about that.

The question I think you’re asking is:

Will n = (3 * n) + 1; ever overflow?

That can be answered as an inequality:

  • If (3 * n) + 1 > UINT64_MAX, then you have Overflow.

And that is an inequality you can solve algebraically.

  • If (3*n) > UINT64_MAX-1, then you have Overflow
  • If n > (UINT64_MAX-1)/3, then you have Overflow

So, ultimately, if n > (UINT64_MAX-1)/3 (or approximately 6.1489e18), then you cannot complete the calculation without overflowing uint64_t.

Read more here: Source link