Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment X Mod N in One Line

Tags:

java

c

I have several small programs that require infinitely looping over the integer set Z sub n. I often write the code in this manor:

int x = 0;
int n = 13; //or some other prime
while(1) {
  //do stuff dependent on x
  ++x;
  x %= n;
}

I write code mostly in C/C++ & Java so I was wondering:

Is there a way to increment x mod n in one line rather then two in either language?

like image 997
recursion.ninja Avatar asked Dec 08 '12 00:12

recursion.ninja


4 Answers

Have you considered:

x = (x + 1 == n ? 0: x + 1);

The chances are the x + 1 will optimise to one instruction and at least you are guaranteed to never use division (which a bad optimiser might use when % is involved).

like image 136
OldCurmudgeon Avatar answered Oct 06 '22 12:10

OldCurmudgeon


x = (x + 1) % n;

Not terribly surprising.

like image 40
Louis Wasserman Avatar answered Oct 06 '22 12:10

Louis Wasserman


Another alternative is this

x = ++x % n;  // Java
like image 3
xagyg Avatar answered Oct 06 '22 14:10

xagyg


if (++x == n) x = 0;

Using x = (x + 1 == n ? 0 : x + 1); requires two additions: one for the comparison and another when the value of x is set to x + 1.

like image 2
Nicholas Lindan Avatar answered Oct 06 '22 12:10

Nicholas Lindan