## chihuyu

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;

}

## VernonDozier 2,218

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.

## technogeek_42 -20

please wrap ur code

## technogeek_42 -20

i think use a long

## ithelp 757

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

## zoner7 22

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

## invisal 381

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;

## WaltP 2,905

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.

## technogeek_42 -20

what if use a looping in that problem