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

前端 未结 7 1582
清歌不尽
清歌不尽 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:56

    What about

    (1 - (n%2)) - (n%2)
    

    n%2 most likely will be computed only once

    UPDATE

    Actually, simplest and most correct way would be using table

    const int res[] {-1, 1, -1};
    
    return res[n%2 + 1];
    

提交回复
热议问题