Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is modulus defined the way it is in programming languages

I'm not asking about the definition but rather why the language creators chose to define modulus with asymmetric behavior in C++. (I think Java too)

Suppose I want to find the least number greater than or equal to n that is divisible by f.

If n is positive, then I do:

if(n % f)
   ans = n + f - n % f;

If n is negative:

ans = n - n % f;

Clearly, this definition is not the most expedient when dealing with negative and positive numbers. So why was it defined like this? In what case does it yield expediency?

like image 539
Ted Tool Avatar asked Nov 04 '22 14:11

Ted Tool


1 Answers

Because it's using "modulo 2 arithmetic", where each binary digit is treated independently of the other. Look at the example on "division" here

like image 97
paulsm4 Avatar answered Nov 15 '22 19:11

paulsm4