Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I could use an explanation of MODULUS 2

Status
Not open for further replies.

javierdlm001

Technical User
Jun 28, 2008
264
CA
I have read a few definitions, and seen many examples.
Part of them do make sense, but not completely.
So far the best definition I've seen is this one:
developer.mozilla.org said:
"The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2"
...returns the remainder left over... (of a division)

What "remainder left over" ?
How can there be such thing on the first place?
Maybe I'm not looking at it from the right angle.

I was hoping someone could offer a different definition/approach.

Thanks in advance guys
 
What do you get if you divide 10 by 3?
=>3 and a remainder of 1.

This works for whole numbers only. If one number is a multiple of the other, the modulo is 0. Example: 8 divided by 2 gives 4. No remainder.
9 divided by 2 gives 4, remainder 1. <= This is your modulo right there.

"Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family." (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.
 
Excellent!
This is what I needed!
In another words: Fit the smaller number as many times as possible into the larger, and what's left is the remainder.

However, one of the examples at Mozilla, is this one:

2 % 3 // 2

Based on the what I understood from your example, I would have thought that: (2 fits once into 3, with a left over of 1). But seen the example above I can infer I am not getting it.
 
You need to pay attention to the *order* in which the numbers are presented. In this example it is how often does "3 fit into 2"? => 0 times, the 2 remains.

"Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family." (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.
 
Now I see!
So, if the right number won't fit into the left one, then the left one remains.

Thank you so much MakeItSo :)
 
Just be aware that the javascript modulus operator, like many of the programming languages have the 1950's Fortran bug - it gives the incorrect answer on negative numbers.

-10 % 3 should be 2, not -1
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top