4 ms·
I don't know which one is faster, but I know that one is not correct (squared approach).
by throwaway744678 4y ago
I don't know which one is faster, but I know that one is not correct (squared approach).
- saghm 4y agoWouldn't the second one also potentially be incorrect due to overflow?
- pjscott 4y agoYes. Suppose that both numbers are positive, that x>num, and that x+num is bigger than INT_MAX. In that case we hit signed integer overflow, which is undefined behavior. If signed integer overflow happens to wrap around, which it might, then the result could be negative and the function would return the wrong result. Or anything else could happen; undefined behavior is undefined. In practice, just writing "abs(num) > x" gives quite good machine code, and it does so without introducing hard-to-see bugs.
- deleted 4y ago[deleted]