General modulo-question

  • Thread starter Christian Kruggel
  • Start date
C

Christian Kruggel

Hi!

I try to do some basic programming and got stuck with the
modulo-operator an the problem how to shift any number n into the
interval [b;e] with b < 0 and e > 0.

My first approach was to calculate the spread of [b;e] by e - b and
then to calculate n % spread. Unfortunately this just works for
numbers that are already in [b;e] while other numbers smaller than b
and greater than e are not shifted correctly.

Has anybody programmed such calculation already and could give me a
helping hint?

Christian
 
B

Brad BARCLAY

Christian said:
Hi!

I try to do some basic programming and got stuck with the
modulo-operator an the problem how to shift any number n into the
interval [b;e] with b < 0 and e > 0.

My first approach was to calculate the spread of [b;e] by e - b and
then to calculate n % spread. Unfortunately this just works for
numbers that are already in [b;e] while other numbers smaller than b
and greater than e are not shifted correctly.

Has anybody programmed such calculation already and could give me a
helping hint?

It might be easier to first treat the interval as being [0;e-b], and
then do the modulus (n-b)%(e-b). You should then be able to shift this
back down into your desired range by adding b.

Would that satisfy your requirement?

Brad BARCLAY
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top