提问者:小点点

什么是最快的方法来确定一个数字是偶数还是奇数?


什么是最快的方法来确定一个数字是偶数还是奇数?


共3个答案

匿名用户

众所周知

static inline int is_odd_A(int x) { return x & 1; }

static inline int is_odd_B(int x) { return x % 2; }

但是在打开优化器的情况下,is_odd_b会不会与is_odd_a没有什么不同呢? 否-使用GCC-4.2-O2,我们得到,(在ARM装配中):

_is_odd_A:
    and r0, r0, #1
    bx  lr

_is_odd_B:
    mov r3, r0, lsr #31
    add r0, r0, r3
    and r0, r0, #1
    rsb r0, r3, r0
    bx  lr

我们看到is_odd_bis_odd_a多用3条指令,主要原因是因为

((-1) % 2) == -1
((-1) & 1) ==  1

但是,以下所有版本都将生成与is_odd_a相同的代码:

#include <stdbool.h>
static inline bool is_odd_D(int x) { return x % 2; }      // note the bool
static inline int  is_odd_E(int x) { return x % 2 != 0; } // note the !=

这是什么意思? 优化器通常非常复杂,对于这些简单的东西,最清晰的代码足以保证最佳效率。

匿名用户

通常的做法:

int number = ...;
if(number % 2) { odd }
else { even }

备选方案:

int number = ...;
if(number & 1) { odd }
else { even }

在GCC 3.3.1和4.3.2上进行测试时,两者的速度(没有进行编译器优化)与指令(在x86上编译)的结果差不多--我知道使用div指令求模会慢得多,因此我根本没有测试它。

匿名用户

bool is_odd = number & 1;