I've got some code that calculates a cyclic offset for a given integer, and I want it to calculate the cyclic-offset such that the function's output will not show any anomalous behavior as the input value transitions from positive to negative and back.
Here's my current implementation, which appears to work correctly, AFAICT:
#include <stdio.h>
unsigned int PositiveModulus(int value, unsigned int divisor)
{
if (value < 0)
{
const int numCyclesToAdd = 1+((-value)/divisor);
value += numCyclesToAdd*divisor;
}
return value%divisor;
}
// unit test
int main(int argc, char ** argv)
{
for (int i=-10; i<=10; i++) printf("%i -> %u\n", i, PositiveModulus(i,5));
return 0;
}
... in particular, when I run the above, I get the following output, which demonstrates the behavior I want:
$ ./a.out
-10 -> 0
-9 -> 1
-8 -> 2
-7 -> 3
-6 -> 4
-5 -> 0
-4 -> 1
-3 -> 2
-2 -> 3
-1 -> 4 // note output transitions from 4 to 0 on these two
0 -> 0 // lines, just like every other iteration of the cycle
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 0
6 -> 1
7 -> 2
8 -> 3
9 -> 4
10 -> 0
My question is, does this function have a well-known/official name? (Searching for "positive modulus" returns some results, but the function described in those results doesn't seem to behave the same as the above code)
... and a bonus question is: Is the function shown above the best way to implement this behavior, or is there another approach that is more concise and/or mathematically correct?