나눗셈의 나머지 값을 구하는 것이 모듈러(Modulo) 연산입니다.

 

\[ a\% b = r \]

여기서 a 또는 b가 음수가 되면 결과는 어떻게 될까요?

답은 "구현마다 다르다(Implementation-defined)" 입니다.

 

From ISO14882:2003(e)

If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

C++03에서는 구현 따라 다르다고 되어 있고요

 

From ISO14882:2011(e) 5.6-4:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

C++11에서는 \(a=(a/b)*b+a\% b\)가 되게 하도록 \(a \% b\)의 부호를 정한다고 하네요.

 

또 언어마다 다릅니다. (링크)

부호가 몫의 부호를 따르거나, 나누는 수의 부호를 따르거나, 무조건 음이 되지 않도록(nonnegative always) 하거나, 구현에 맡겨버리는 경우도 있습니다. 복잡하네요.

 

예를 들어 \(-5 \% 4\)를 C++17, Python 3에서 구해보면 아래와 같이 나옵니다.

  • C++17: -1
  • Python 3: 3

 

음수 모듈러 연산이 일어나지 않도록 구현해야 의도치 않은 결과가 나오지 않겠죠?

반응형

'수학 > 정수론' 카테고리의 다른 글

약수의 개수, 약수의 합  (0) 2020.07.03
소수를 구하는 방법  (0) 2020.04.09
최대공약수(GCD)와 최소공배수(LCM)  (0) 2020.04.09
큰 수의 모듈러 연산  (0) 2020.03.24