2
$\begingroup$

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?

$\endgroup$

closed as off-topic by D.W., David Richerby, Raphael Apr 29 '14 at 8:34

This question appears to be off-topic. The users who voted to close gave these specific reasons:

  • "This question does not appear to be about computer science, within the scope defined in the help center." – Raphael
  • "Questions about software development or programming tools are off-topic here, but can be asked on Stack Overflow." – D.W., David Richerby
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    $\begingroup$ 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 Stack Overflow or Mathematics? $\endgroup$ – Raphael Apr 29 '14 at 8:34
6
$\begingroup$

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").

$\endgroup$
  • 1
    $\begingroup$ With signed integers it becomes messy and different programming languages use a different operator. $\endgroup$ – chi Jul 24 '18 at 12:18
-3
$\begingroup$

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.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.