0

I am trying to make something like this:

2^1 + 2^2 + 2^3 + 2^4 + ... + 2^n

This is my code:

#include <iostream>

int main(){
    int n, p=0;
    std::cout<<"N: ";
    std::cin>>n;
    
    for(int i=1; i<=n; i++){
        p = p+(2^i);
    }
    std::cout<<p;

    return 0;
}

The result is always incorrect. If I input 4, the result is 10. If I input 5, the result is 17 I think the problem is in p = p+(2^i); but I am not sure.

2 Answers2

0

In c++ ^ is a bitwise operator, not the power symbol. You should use the pow() function from the standard library. You should check this answer.

0

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  
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • Thanks you! Can I ask what is the difference between `int` and `unsigned int`? –  Feb 05 '21 at 00:18
  • Simply speaking the `int` type reserves the most significant bit to indicate the number is negative. With unsigned int, all bits are available, but the number can't be negative. Unsigned int is used for wider range and when playing with bits (like 1 << n). – Thomas Matthews Feb 05 '21 at 00:26