The remainder of integer division by 0

Consider integer division

a = bq + r 

where a, b, q, r - respectively: dividend, divider, coefficient and remainder. In particular, when b = 0, there is no unique q satisfying the equation for a given a, and therefore it makes sense that in this case the factor q must be undefined.

However, in this case there really exists such r, namely r = a. Assuming that the factor and the remainder are always determined together, it follows that r is not determined when q is undefined, but when programming we often want to use the remainder % operation regardless of the division of / , I really came across a situation where I want if b == 0 then a else a % b end .

Is there / is any operator in any programming language, so that it matches % , but returns a dividend instead of a zero division error when the divisor is 0?

Is there a reason why most (or all) programming languages โ€‹โ€‹return a zero division error for % 0 ?

+4
source share
2 answers

Mathematically, the remainder is between 0 and b-1, where b is the divisor. Therefore, when b = 0, r is undefined, since it must be> = 0.

+2
source

Is there any programming language that returns a dividend? Not sure. I have never come across them.

Is there a reason why most do not return the dividend? Yes A module is a common operation in CS because it is a by-product of integer division by CPU. Most (if not all) assembler languages โ€‹โ€‹have a module function, and this operation uses the same hardware as the division operation. Thus, if you cannot divide by zero by hardware, then you cannot use the null module in hardware.

Does this mean that you cannot have a language that supports this? Not really, but you need to add an if statement to the operation, which is usually a single statement. This is likely to lead to a pretty strong performance hit, so few (if any) will.

+2
source

Source: https://habr.com/ru/post/1347273/


All Articles