I require symmetric modulo operator for balanced ternary number system; It can be used to calculate least significant trit of trits sum (ternary addition function); My implementation seems inefficient, it uses 2 modulo(%) operators, and several addition/substraction operations. Here is my code (it works correctly):
int symmetric_modulo( int x, int fullRadix = 3 ) {
int halfRadix = fullRadix / 2;
int divRemainder = x % fullRadix;
return ( divRemainder + halfRadix + fullRadix ) % fullRadix - halfRadix;
}
x may be in range [-3..3]; and result should be -1, 0 or 1; Can you offer more efficient code to do this?