将整数除以16而不使用除法或强制转换

时间:2010-12-31 17:21:44

标签: optimization division fractions

好的......让我改一下这个问题......

如何在不使用除法或转换加倍的情况下获得整数的x 16;

5 个答案:

答案 0 :(得分:5)

int res = (ref * frac) >> 4

(但是担心一点溢出。参考和压裂有多大?如果它可能溢出,先抛出更长的整数类型)

答案 1 :(得分:2)

在任何这种类型的操作中,首先乘以然后除以是有意义的。现在,如果您的操作数是整数并且您使用的是可编译语言(例如C),请使用shr 4而不是/ 16 - 这将节省一些处理器周期。

答案 2 :(得分:0)

假设这里的所有内容都是整数,任何值得盐的优化编译器都会注意到16是2的幂,并且相应地移动frac - 只要打开优化即可。担心编译器无法为您做的主要优化。

如果有的话,你应该括号ref * frac然后得到除法,因为任何小于16的压裂值都会导致0,无论是通过移位还是除法。

答案 3 :(得分:0)

您可以使用左移或右移:

public static final long divisionUsingMultiplication(int a, int b) {
    int temp = b;
    int counter = 0;
    while (temp <= a) {
        temp = temp<<1;
        counter++;
    }
    a -= b<<(counter-1);
    long result = (long)Math.pow(2, counter-1);
    if (b <= a) result += divisionUsingMultiplication(a,b);
    return result;
}

public static final long divisionUsingShift(int a, int b) {
    int absA = Math.abs(a);
    int absB = Math.abs(b);
    int x, y, counter;

    long result = 0L;
    while (absA >= absB) {
        x = absA >> 1;
        y = absB;
        counter = 1;
        while (x >= y) {
            y <<= 1;
            counter <<= 1;
        }
        absA -= y;
        result += counter;
    }
    return (a>0&&b>0 || a<0&&b<0)?result:-result;
}

答案 4 :(得分:-1)

我不理解约束,但这个伪代码向上舍入(?):

res = 0
ref= 10
frac = 2
denominator = 16
temp = frac * ref
while temp > 0
   temp -= denominator
   res += 1
repeat
echo res