3 ms·
The problem can be perfect depending on how it's stated. If you spell out the contract right, then it can be perfect. Some examples: Given two 32-bit signed in
by int_19h 8y ago
The problem can be perfect depending on how it's stated. If you spell out the contract right, then it can be perfect. Some examples:
Given two 32-bit signed integers, produce a 32-bit signed integer that is a sum of the inputs; if the sum doesn't fit into 32 bits, wrap modulo 32 bits.
Given two 32-bit signed integers, produce a 64-bit signed integer that is a sum of the inputs.
Given two 32-bit signed integers, produce either a 32-bit signed integer that is a sum of the inputs if it fits into 32 bits, or an error code indicating that it did not fit.
The problem with languages like C is that they let you be imprecise and get away with in. If you just run with "add two signed 32-bit integers", and implement it as "x + y" in C, it will compile, and it will run, but the result is undefined behavior if it overflows (note: it doesn't even mean that you get the wrong value - it can literally do anything at all). In Zig, if you write it as "x + y", it will panic on overflow, which is at least well-defined and fails fast; and the language provides you with tools to implement any of the three properly defined scenarios above in straightforward ways (i.e. you can add with wraparound, or you can add with an overflow check).