如何实现对称模运算?

时间:2015-07-27 15:34:52

标签: c ternary

我需要对称模运算符来实现平衡三元数系统;它可用于计算最小有效三次总和(三元加法函数);我的实现似乎效率低下,它使用2个模数(%)运算符和几个加法/减法运算。这是我的代码(它可以正常工作):

int symmetric_modulo( int x, int fullRadix = 3 ) {
    int halfRadix = fullRadix / 2;
    int divRemainder = x % fullRadix;
    return ( divRemainder + halfRadix + fullRadix ) % fullRadix - halfRadix;
}

x可以在[-3..3]范围内;结果应为-1,0或1; 你能提供更有效的代码吗?

1 个答案:

答案 0 :(得分:2)

int divRemainder = x % fullRadix;仅在x + halfRadix + fullRadix溢出或结果为负时才需要。

如果没有溢出/否定结果,如x may be in range [-3..3];简化:

int symmetric_modulo(int x, int fullRadix) {
    int halfRadix = fullRadix / 2;
    return (x + halfRadix + fullRadix) % fullRadix - halfRadix;
}