We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Modulo/Modular arithmetic confusion
Page Index Toggle Pages: 1
Modulo/Modular arithmetic confusion (Read 483 times)
Modulo/Modular arithmetic confusion
Nov 2nd, 2008, 8:31pm
 
Say I have the numbers 1 to 12 around a circle, like on a clock face. I am trying to write a function where you can input A and B between 1 and 12 and it will output C, so that if you start at 12 O'clock and go around by A, then around by C, you end up at B ...but in the direction which is shortest.

So if clockwise is positive:

if A = 2  and B = 5  then  C =  3
if A = 2  and B = 11 then  C = -3
if A = 11 and B = 2  then  C =  3
if A = 4  and B = 3  then  C = -1

I thought maybe I could use

D = (B-A) mod 12
then IF D<6 C = D
but  IF D>6 C = D-12

but I am confused about the difference between 'modulo' / '%' / 'remainder' / 'modular arithmetic'

Can anyone shed some light on this?
Re: Modulo/Modular arithmetic confusion
Reply #1 - Nov 3rd, 2008, 8:26am
 
I have decent results with following code:
Code:
for (int i = 1; i <= 12; i++)
{
for (int j = 1; j <= 12; j++)
{
int d = j - i;
if (d > 6) d = d % 6 - 6;
else if (d < -6) d = d % 6 + 6;
println(i + " " + j + " " + d + " " + (i - j + d));
}
}
exit();

You might want to tune the results when getting 6 or -6, but at least it seems to be correct.
Re: Modulo/Modular arithmetic confusion
Reply #2 - Nov 3rd, 2008, 11:44am
 
That works great, just what I needed.
Thanks!
Page Index Toggle Pages: 1