Hello,I am new for C++.The following are the codes I wrote to calculate the sum of 2^n. The result is 2046 after running the program.That is correct. But when I change the condition to n<=100,the result comes with -2,which is obviously wrong.Then I tried different n and found if n<=30,the right result can be obtained but if n>=31 the result is always -2.Can someone tell me where my mistake lies and how I can solve it? Thank you.

#include<iostream> 

int main()

{

    int n=1,a=1,sum=0;

    while(n<=10) {

        a=2*a;

        sum=sum+a;

        n=n+1;

    }

    std::cout <<"The result is "<<sum
 
              <<std::endl;



    return 0;

}

You're probably going past the bounds of what an integer can store and getting an overflow. An integer in a 32 bit system overflows at 2^31, I believe. It cannot hold anything higher than that.

please wrap ur code

i think use a long

Use link list to represent big number else overflow will happen.

I'm not sure if you care or not, but your sum variable does not include the value when n = 0 (1).

This is off-topic, but it is good thing to know. 2^n can be easily done by using bitwise operator.

a = 1;
a =<< n;

Hello,I am new for C++.The following are the codes I wrote to calculate the sum of 2^n. The result is 2046 after running the program.That is correct. But when I change the condition to n<=100,the result comes with -2,which is obviously wrong.Then I tried different n and found if n<=30,the right result can be obtained but if n>=31 the result is always -2.Can someone tell me where my mistake lies and how I can solve it? Thank you.

You don't have a problem, just lack of knowledge, as described by VernonDozier.

You're probably going past the bounds of what an integer can store and getting an overflow. An integer in a 32 bit system overflows at 2^31, I believe. It cannot hold anything higher than that.

This is exactly what the problem is...

please wrap ur code

In what? Saran Wrap?

i think use a long

int and long are identical in most compilers today.

Use link list to represent big number else overflow will happen.

Did you miss the first 6 words of the OP's post? And linked lists don't fix overflows.

what if use a looping in that problem

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.