Having trouble understanding

In the book that I'm reading (Dive into C++)
the author says
If you divide your
random number by the size of the range, you'll end up getting a number between 0 and the size of the
range (but never including the size of the range)


I've tested this with a bunch of numbers and it's true but I don't understand why it works.

11 % 3 = 2 2 is in the rage [0,3)

55 % 6 = 1 1 is in the range [0, 6)

So pretty much p % n is going to be in the range of [0, n), but why is that?

I'm really puzzled and I hope someone can break it down for me. All help is appreciated.
Think about what n % n is.
% or the modulus operator basically is this p % n can be looked at like this divide p by n and then the remainder is given.

or we can write it like this

1
2
while( p > n )
    p -= n;


Basically say we have 27 % 2 this would mean
27 / 2 = 13 / 2 = 6/2 = 3/2 = 1

Basically we divide then round down since it takes int not double

Another method would be to do

1
2
3
4
while( p > n )
{
     p /= n;
}


Basically dividing and subtracting is the same if you think about it. and an int divided by an int is an int and not a double.


What I mean by dividing and subtracting being the same is that think about it

12 / 4
=
12 - 4 = 8 -> 1
8 - 4 = 4 -> 2
4 - 4 = 0 -> 3

answer is 3 ( we subtracted as many times as we could )
This is how int divisions work
[edit]if you did 12 % 4 that 0 that is left over would be the result.[/edit]

Lets look at another

15 / 2

15 - 2 = 13 -> 1
13 - 2 = 11 -> 2
11 - 2 = 9 -> 3
9 - 2 = 7 -> 4
7 - 2 = 5 -> 5
5 - 2 = 3 -> 6
3 - 2 = 1 -> 7

1 is less than 2 so answer would be 7
[edit]if you did 15 % 2 that 1 that is left over would be the result.[/edit]

Anyways hopefully I didn't confuse you but % operator means just divide as many times as you can then return the remainder.


http://www.cprogramming.com/tutorial/modulus.html
http://www.cplusplus.com/doc/tutorial/operators/
http://stackoverflow.com/questions/12556946/how-does-the-modulus-operator-work
Last edited on
Thank you.
Topic archived. No new replies allowed.