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

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

    First of all, the fastest isOdd test I do know (in an inline method)

    /**
    * Return true if the value is odd
    * @value the value to check
    */
    inline bool isOdd(int value)
    {
    return (value & 1);
    }
    

    Then make use of this test to return -1 if odd, 1 otherwise (which is the actual output of (-1)^N )

    /**
    * Return the computation of (-1)^N
    * @n the N factor
    */
    inline int minusOneToN(int n)
    {
    return isOdd(n)?-1:1;
    }
    

    Last as suggested @Guvante, you can spare a multiplication just flipping the sign of a value (avoiding using the minusOneToN function)

    /**
    * Example of the general usage. Avoids a useless multiplication
    * @value The value to flip if it is odd
    */
    inline int flipSignIfOdd(int value)
    {
    return isOdd(value)?-value:value;
    }
    

提交回复
热议问题