什么是找到一个数是偶数或奇数的最快方法?

编程入门 行业动态 更新时间:2024-10-28 12:23:34
本文介绍了什么是找到一个数是偶数或奇数的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

什么是找到最快的方法,如果一个号码偶数或奇数?

What is the fastest way to find if a number is even or odd?

推荐答案

有pretty众所周知,

It is pretty well known that

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汇编):

But with the optimizer on, will is_odd_B be no different from is_odd_A? No — with gcc-4.2 -O2, we get, (in ARM assembly):

_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_B 花费的时间比 is_odd_A 3的更多说明,主要的原因是因为

We see that is_odd_B takes 3 more instructions than is_odd_A, the main reason is because

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

然而,下面所有的版本将生成相同的code作为 is_odd_A :

However, all the following versions will generate the same code as 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 !=

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

更多推荐

什么是找到一个数是偶数或奇数的最快方法?

本文发布于:2023-06-01 10:28:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/413035.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:奇数   偶数   个数   最快   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!