Many algorithms need to calculate the (- 1) ^ n
(both integers) It is usually the factor in a series, a factor which is also odd for -1
and n for 1
in the C or C ++ environment, a Often sees:
#include & lt; Iostream & gt; #to & lt include, cmath & gt; Int main () {int n = 13; Std :: cout & lt; & Lt; Std :: pow (-1, n) & lt; & Lt; Std :: endl; }
What is a better or general conference? (or something else),
std :: pow (-1, N) std :: pow (-1, n% 2) (n% 2? -1: 1) (1-2 * (n% 2)) // (returns the wrong value for negative n)
Edit: Additionally, user @ sievenepeddude has another alternative ( A universal?) Is my version of Array Lookup, which is proposed:
const int res [] {-1, 1, -1}; // Three elements are required for negative elements const int * const m1pow = res + 1; ... m1pow [n% 2]
you (n & amp; ; 1) instead of
instead of n% 2
and
& Lt; 1 * 2
If you want to be a highly educated, I mean optimized.
Therefore, the fastest way to calculate in an 8086 processor is:
1 - ((n & amp; 1)
< / P>
I have to make clear that where this answer is coming from, original poster Alfisi had an excellent job of posting several different methods to calculate (1) ^ n Some others compare Are fast in
As fast as the processor is taking place today, we make readability of some CPU cycles from shaving with a lesser (even more insignificant) improvement from shaving to usually .
There was a time when a pass compiler ruled the earth and the MUL operation was new and downgrade; In those days, the operation of 2 operations was an invitation to redundant optimization.
No comments:
Post a Comment