Notice that each term is a power of 2, which can be represented using the left shift operator:
for (int i = 0; i < N; ++i)
{
p = p + (1 << i);
}
You could also note that each term is 2 times the previous term.
Thus you could write it also as:
unsigned int term = 1;
unsigned int sum_of_terms = 0;
for (int i = 0; i < N; ++i)
{
sum_of_terms += term;
term *= 2;
}
Edit 1: The Exclusive Or truth table
The operator^
is the **Exclusive-Or` operator. It works with bits.
Here's the truth table based on two bits:
X | Y | X ^ Y
------------------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…