开发者

Why is modulus defined the way it is in programming languages

开发者 https://www.devze.com 2023-04-05 17:10 出处:网络
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)

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?


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


You're mistaken. When n is negative, C++ allows the result of the modulus operator to be either negative or positive as long as the results from % and / are consistent, so for any given a and b, the expression (a/b)*b + a%b will always yield a. C99 requires that the result of a % b will have the same sign as a. Some other languages (e.g., Python) require that the sign of a % b have the same sign as b.

This means the expression you've given for negative n is not actually required to work in C++. When/if n%f yields a positive number (even though n is negative), it will give ans that's less than n.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号