What is the correct way to obtain (-1)^n?

前端 未结 7 1660
清歌不尽
清歌不尽 2021-01-31 07:19

Many algorithms require to compute (-1)^n (both integer), usually as a factor in a series. That is, a factor that is -1 for odd n and 1 fo

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 07:54

    If it's speed you need, here goes ...

    int inline minus_1_pow(int n) {
        static const int retvals[] {1, -1}; 
        return retvals[n&1];
    }
    

    The Visual C++ compiler with optimization turned to 11 compiles this down to two machine instructions, neither of which is a branch. It optimizes-away the retvals array also, so no cache misses.

提交回复
热议问题