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

前端 未结 7 1584
清歌不尽
清歌不尽 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 08:00

    You can use (n & 1) instead of n % 2 and << 1 instead of * 2 if you want to be super-pedantic, er I mean optimized.
    So the fastest way to compute in an 8086 processor is:

    1 - ((n & 1) << 1)

    I just want to clarify where this answer is coming from. The original poster alfC did an excellent job of posting a lot of different ways to compute (-1)^n some being faster than others.
    Nowadays with processors being as fast as they are and optimizing compilers being as good as they are we usually value readability over the slight (even negligible) improvements from shaving a few CPU cycles from an operation.
    There was a time when one pass compilers ruled the earth and MUL operations were new and decadent; in those days a power of 2 operation was an invitation for gratuitous optimization.

提交回复
热议问题