Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remainder of integer division by 0

Consider integer division

a = bq + r

where a, b, q, r are respectively: dividend, divisor, quotient, and remainder. Particularly when b = 0, there is no unique q that satisfies the equation for a given a, and hence it makes sense that the quotient q should be undefined in such case.

However, there is indeed a unique r in such case, namely, r = a. Under the premise that the quotient and the remainder are always defined together, it would follow that r is not defined whenever q is undefined, but in programming, we often want to use the remainder operation % irrespective of division /. I actually came across a situation where I want if b == 0 then a else a % b end.

Is there/Was there an operator in any programming language such that it is the same as % but returns the dividend instead of a zero division error when the divisor is 0?

Is there any reason that most (or all) programing languages return a zero division error for % 0?

like image 832
sawa Avatar asked Oct 12 '22 08:10

sawa


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 has to be >= 0.

like image 86
pjwilliams Avatar answered Oct 18 '22 04:10

pjwilliams


Is there any programming language that returns the dividend? Not sure. I've never come across any.

Is there a reason that most don't return the dividend? Yes. Modulus is a common operation in CS because it is a byproduct of integer division on a CPU. Most (if not all) assembly languages have a modulus operation, and this operation uses the exact same hardware as the division operation. Thus if you can't divide by zero in hardware, then you can't do modulus zero in hardware.

Does this mean that you can't have a language that supports this? Not really, but you would have to add an if-statement to an operation that is usually a single instruction. This would probably result in a pretty heavy performance hit, so few (if any) do it.

like image 35
riwalk Avatar answered Oct 18 '22 03:10

riwalk