0

trying to make a program that can calculate 2^n, 1<=n<=100,but I have some major issues in my code.The problem appears when n>=5

#include <iostream> using namespace std; int main() { int n,v[31]={2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},a=0; cin>>n; for(int i=1;i<n;i++) { for(int j=0;j<31;j++) { if(v[j]*2+a>9) { a=(v[j]*2+a)/10; v[j]=(v[j]*2+a)%10; } else { v[j]=(v[j]*2)+a; a=0; } } } for(int i=30;i>=0;i--)cout<<v[i]; return 0; }

14th Dec 2016, 10:14 PM
Catalin Dervesteanu
Catalin Dervesteanu - avatar
5 Answers
+ 2
Why don't do something like this: result = 2; for (i=n;i<=0;i--){ result *=2 }
14th Dec 2016, 10:44 PM
Nahuel
Nahuel - avatar
+ 1
I know where the mistake is. In the first part of the if statement you are using the already modified a. Just replace it with this and everything should work fine. ... if(v[j]*2+a>9){ v[j]=(v[j]*2+a); a = v[j]/10; v[j] = v[j]%10; } ...
14th Dec 2016, 10:51 PM
Martin BrezĂĄni
Martin BrezĂĄni - avatar
+ 1
No problem :)
14th Dec 2016, 10:59 PM
Martin BrezĂĄni
Martin BrezĂĄni - avatar
0
because the size of the number is too big , 2^100 has 31 digits and the biggest data type I know, the unsigned long long has 19 digits (if I remember well)
14th Dec 2016, 10:48 PM
Catalin Dervesteanu
Catalin Dervesteanu - avatar
0
worked like a charm, thank you Martin
14th Dec 2016, 10:58 PM
Catalin Dervesteanu
Catalin Dervesteanu - avatar