tags:

views:

693

answers:

7

I'm embarrassed to ask such a simple question. My term does not start for two more weeks so I can't ask a professor, and the suspense would kill me.

2/4 = .5 so why does 2 mod 4 = 2?

Sorry if I'm missing something obvious.

Thanks!

+5  A: 

Modulo (mod, %) is the Remainder operator.

2%2 = 0 (2/2 = 1 remainder 0)
1%2 = 1 (1/2 = 0 remainder 1)
4%2 = 0 (4/2 = 2 remainder 0)
5%2 = 1 (5/2 = 2 remainder 1)
phsr
And "verbose" explanation: 2 = 4·0 + 2 ;-)
Michael Krelin - hacker
+3  A: 

mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.

DaveJohnston
+29  A: 

Modulo is the remainder, not division.

2 / 4 = 0R2
2 % 4 = 2

The sign % is often used for the modulo operator, in lieu of the word mod.

For x % 4, you get the following table (for 1-10)

 x x%4
------
 1  1
 2  2
 3  3
 4  0
 5  1
 6  2
 7  3
 8  0
 9  1
10  2
Eric
Link + definition + example == +1
tvanfosson
That was easily my favorite downvote ever, whoever you are.
Eric
+18  A: 

Mod just means you take the remainder after performing the division. Since 4 goes into 2 zero times, you end up with a remainder of 2.

Jarsen
Thanks! I just needed to hear it talked all the way through.
NewToThis
+4  A: 

2 / 4 = 0 with a remainder of 2

Joe Doyle
A: 

For a visual way to think about it, picture a clock face that, in your particular example, only goes to 4 instead of 12. If you start at 4 on the clock (which is like starting at zero) and go around it clockwise for 2 "hours", you land on 2, just like going around it clockwise for 6 "hours" would also land you on 2 (6 mod 4 == 2 just like 2 mod 4 == 2).

Anon
That's actually pretty confusing.
Joe Philllips
@do3boy: the idea of the clock face is a very simple and easy method to describe exactly the fact of the modulo. except that it would have been easier to use 24h format for explaining it instead of modifying the number of available positions.
Atmocreations
+3  A: 

As all the above comments have mentioned is the fact that its the remainder.

i just wanted to put my 2 pence on where i use the "mod" keyword alot in xsl

To get a html table with rows that have alternative colours (Red, Blue, Red, Blue, Red etc...)

i use

<!-- if the rows position is a even number then give it a class of red -->

<xsl:if test="position() mod 2 = 0">
     <xsl:attribute name="class">
            red
     </xsl:attribute>
</xsl:if>


.....

<tr>
<tr class="red">
<tr>
<tr class="red">
<tr>
<tr class="red">
Mike