n /= 2; should never overflow, so I’m not worried about that.
The question I think you’re asking is:
n = (3 * n) + 1; ever overflow?
That can be answered as an inequality:
(3 * n) + 1 > UINT64_MAX, then you have Overflow.
And that is an inequality you can solve algebraically.
(3*n) > UINT64_MAX-1, then you have Overflow
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
Read more here: Source link