Should % ever "overflow"?
Smoke Adams via Digitalmars-d
digitalmars-d at puremagic.com
Sat Jun 25 16:01:00 PDT 2016
On Friday, 24 June 2016 at 20:43:38 UTC, deadalnix wrote:
> On Friday, 24 June 2016 at 20:33:45 UTC, Andrei Alexandrescu
> wrote:
>> In a checked environment, division may "overflow", e.g. -6 /
>> 2u must be typed as uint but is not representable properly one.
>>
>> How about remainder? I suppose one can make the argument that
>> remainder should never overflow (save for rhs == 0), because
>> it could be defined with either a positive or negative
>> denominator (which is not part of the result).
>>
>> What's the most reasonable behavior?
>>
>>
>> Andrei
>
> Most reasonable is
>
> numerator = quotient * divisor + remainder
>
> Which means it can be negative.
This proves nothing.
Wiki:
For a ***positive integer n***, two integers a and b are said to
be congruent modulo n, written:
a ≡ b ( mod n ) , {\displaystyle a\equiv b{\pmod {n}},\,}
a\equiv b{\pmod {n}},\,
if their difference a − b is an integer multiple of n (or n
divides a − b). The number n is called the modulus of the
congruence.
For any "negative" remainder, all one has to do is subtract one
from the divisor:
quotient*(divisor - 1 + 1) + remainder
= quotient*new_divisor + pos_remainder
where new_divisor = divisor - 1, pos_remainder = quotient +
remainder
There are problems with allowing the remainder to be negative and
it is generally best to restrict it to positive values.
e.g., 129 = 2*52 + 25 OR 3*52 - 27.
In the second case, we have 129/52i = 3? Basically by restricting
to positive integers, we have a more natural interpretation and
relationship to floor and ceil functions and we don't have to
worry about it being negative(think of using in in an array
indexing scheme),
More information about the Digitalmars-d
mailing list