c - 向上舍入 n/4 的有效方法

标签 c algorithm math optimization rounding

我有一个整数 n,我需要向上取整 n/4。出于性能原因,我需要在 C 中找到一种快速的方法。除以 4 可以使用 >> 2 移位操作来完成,但我不知道该轮次。我可以使用 ceil,但我担心性能。

最佳答案

如果你的操作数是非负的,怎么样:

unsigned int
roundupdiv4 (unsigned int n)
{
    return (n+3)>>2;
}

请注意,无论如何,任何明智的编译器都会将 unsigned int/4 编译为 >>2

我可以通过使用 gcc -O3 -S 编译上面的代码来确认:

    .file   "x.c"
    .text
    .p2align 4,,15
    .globl  roundupdiv4
    .type   roundupdiv4, @function
roundupdiv4:
.LFB0:
    .cfi_startproc
    leal    3(%rdi), %eax
    shrl    $2, %eax
    ret
    .cfi_endproc
.LFE0:
    .size   roundupdiv4, .-roundupdiv4
    .ident  "GCC: (Ubuntu 4.8.2-19ubuntu1) 4.8.2"
    .section    .note.GNU-stack,"",@progbits

如果我将 >>2 替换为 /4,请注意输出完全相同

另请注意,我使用了 unsigned int 作为 >>> 是为负符号左操作数(即向右移动负值)定义的实现。如果您想要一个可以(严格向上)为有符号值四舍五入的工作:

int
roundupdiv4 (int n)
{
    return ((n>0)?(n+3):n)/4;
}

因为整数除法使用截断舍入,即无论如何都会对负数(接近零)进行舍入。 (这是针对 C99 onwards 的;它是在 C89 中定义的实现)。

如果四舍五入是指“从零开始四舍五入”,那么:

int
roundawayfromzerodiv4 (int n)
{
    return ((n>0)?(n+3):(n-3))/4;
}

关于c - 向上舍入 n/4 的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28305314/

相关文章:

python - Python 3.7 math.remainder 和 %(模运算符) 之间的区别

c - openmp 部分按顺序运行

c - 文件的结束值打印为问号

c - 如何使用灵活的数组成员初始化结构

javascript - 从一组坐标中找到最接近的坐标

algorithm - 面试题: determine whether two linked lists are connected or not

python - 如何在 Python 中计算真正大整数的 exp(x)?

c - 单一源代码与多个文件 + 库

algorithm - 为什么 Induction 总是不适用于 Big-O?

python - 查找不能被 x 到 y 整除的 a 到 b 的数字