Just in case someone else finds it useful: Here is a small implementation on how to do a proper modulo operation in C# and how to calculate the modular distance between two numbers.
If you haven’t been aware, the % operator in most programming languages isn’t the exact equivalent to an arithmetic modulo. In fact, it is simply the remainder of the division between two numbers. Modular arithmetic is a little bit more.
One useful application for the modulo is the modular distance. The modular distance is the distance of two member in a circular space, or a ring. Roughly, it can be understood as the minimum difference between two numbers in this circular space, either going “clockwise” or “counter-clockwise”. For example, in a circle, the modular distance between 1° and 359° is 2° (and not 358°).
public static class Math
// Calculates x in modulo m
public static int Mod(int x, int m)
if (m < 0) m = -m;
int r = x % m;
return r < 0 ? r + m : r;
// Calculates the distance from a to b in modulo m
public static int ModularDistance(int a, int b, int m)
return System.Math.Min(Mod(a - b, m), Mod(b - a, m));