2

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?

xakepp35
  • 2,878
  • 7
  • 26
  • 54
  • If you have a limited and known range for both operands, a simple lookup table will do, if you are not satisfied with the efficiency (but it looks ok to me). – Eugene Sh. Jul 27 '15 at 16:00
  • Thanks, this can do the trick, but.. there is some buts :) LUT approach heavily depends on memory speed; I'm definetely looking for some math way, which is definetely faster on modern processors, when in comes to simple integer math. – xakepp35 Jul 27 '15 at 16:14
  • 2
    You are aware that the code is executed from the same RAM, data fetched is from, right (unless we are talking about some embedded platform)? So if the memory speed is concerning you, it should concern you with code as well. Also mind caches. But anyway, for small LUTs it can be implemented with a switch case rather than with arrays. – Eugene Sh. Jul 27 '15 at 16:16

1 Answers1

2

int divRemainder = x % fullRadix; only needed if x + halfRadix + fullRadix overflows or the result is negative.

If no overflow/negative result possible as in x may be in range [-3..3]; Simplification:

int symmetric_modulo(int x, int fullRadix) {
    int halfRadix = fullRadix / 2;
    return (x + halfRadix + fullRadix) % fullRadix - halfRadix;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256