Rohcana
Rohcana

Reputation: 359

Code works for upto certain point then crashes

The following code is for finding 2^n. It works fine (and gives the correct result) for n<=1307. However it crashes for n>1307. I would like to know where the problem is.

#include <iostream>
#include <cmath>

using namespace std;
const int n=1307;                  //digit sum of 2^n
const int digit= n*log10(2)+5;     //expected no of digits in 2^n (+5 for safety)

int main()
{
    int power[n][digit];    // power[n][k] is the kth digit (from right) of 2^n
    for (int iii=0; iii<=n; iii++)          // initialize every digit to 0
        for (int jjj=0; jjj<digit; jjj++)
            power[iii][jjj]=0;
    power[1][0]=2;                          //set 2^1=2

        //each step calculate 2^n by doubling 2^(n-1)

    for (int iii=2; iii<=n; iii++)
    {
        int carry=0;
        for (int jjj=0; jjj<digit; jjj++)
        {
            int k=2*power[iii-1][jjj];      //temp variable
            power[iii][jjj]=(k+carry)%10;
            carry=(k+carry)/10;
        }
    }


    for (int jjj=digit -1; jjj>=0; jjj--)
        cout << power[n][jjj];
}

There shouldn't be any problems concerning types (int, long), only single digit calculations are taking place. So, where's the problem?

Upvotes: 0

Views: 62

Answers (1)

jensa
jensa

Reputation: 2890

Try running it in a debugger. Moreover, you set

int power[n][digit];

but your loop does

for(int iii=0;iii<=n;++iii)

Index out of bounds when iii = n.

Upvotes: 1

Related Questions