On 01/09/2021 08:54, Barry Schwarz wrote:
> On Wed, 1 Sep 2021 07:31:53 +0200, Joseph Hesse <
jo...@gmail.com>
> wrote:
>
>> The famous unproven Collatz math conjecture says that if you start with
>> any positive integer n and generate a sequence by repeatedly apply the
>> rule that if n is even the next term is n/2, otherwise the next term is
>> 3*n + 1, then eventually the sequence will reach 1.
>>
>> I wrote a C++ function that will generate the sequence from any positive
>> starting integer, see below, header files omitted. Since there is
>> integer arithmetic involved, there might be a math overflow. How does
>> one write code to detect math underflow or overflow errors in functions
>> that do math computations?
>>
> In this particular case, it seems to me to be easier to prevent the
> overflow before it occurs rather than try to detect it after it
> occurs. You could replace the previous assignment with
I agree with that. I've always preferred the "look before you leap"
approach, rather than the "close your eyes, make the jump and let
someone else sweep up the mess" tactic.
(The rest is to the OP, rather than Barry.)
Another option is to use gcc's overflow-detecting builtins, or other
equivalent extensions for other compilers. If you are trying to do this
checking as fast as possible, you might be looking at SIMD support
through compiler vector extensions or processor-specific intrinsics.
For unsigned types, you can of course just do "y = 3 * x + 1;" and check
for "y < x", as the overflow is defined as wrapping.
You would probably also want to use "long long" (or uint64_t), rather
than "long" (which is 32-bit on some systems), as you want big numbers.
You might even want compiler-specific 128-bit types - after all, the
conjecture is known to be true up to at least 2 ^ 68.
The conjecture itself is rather interesting. Here are a couple of
interesting videos on it (there are many, but these are from reliable
and interesting sources, to save you from dry lectures or trisectors who
say they have solved it):
<
https://www.youtube.com/watch?v=094y1Z2wpJg>
<
https://www.youtube.com/watch?v=5mFpVDpKX70>