2

So when you are decrypting an encryption with modular arithmetic, I know the modulus operator (%) gives the remainder of a/b, but what if a is less than b?

For example, 5%2 is 1, since the answer is 2 remainder 1. But for something like 2%9, how do you find the answer?

user17137
  • 29
  • 1
  • 2
  • 1
    Questions about C++ in particular are offtopic here, and the general question is a pure mathematics question. Do you want me to migrate this to [SO] or [math.SE]? – Raphael Apr 29 '14 at 08:34

2 Answers2

7

If $a,b$ are both positive integers, then we can always write $a = kb+\ell$ where $0 \leq \ell < b$. We call $\ell$ the remainder and $k$ the quotient. In your first example, $5 = 2 \cdot 2 + 1$ so 5 % 2 == 1. In your second example, $2 = 0 \cdot 9 + 2$, so 2 % 9 == 2. More generally, if $a < b$ then a % b == a.

There is also a rule for signed integers, but unfortunately I can't remember it. Also, 0 % x == 0 whenever $x \neq 0$, and x % 0 will cause an exception ("division by zero").

Yuval Filmus
  • 276,994
  • 27
  • 311
  • 503
-3

The answer is 9. 2 / 9 is 0r9. The modulus operator returns the remainder of integer division, since 9 goes into 2 0 times the operator returns 9.