Project Euler 14th crashes

maniteja

I'm trying to solve project Euler questions and on the 14th question when i compile it the exe keeps on crashing. Here is my code

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int counter_array[1000000];
    int array_key=0;
    for(int x=1;x<=1000000;x++)
    {
        int y=x;
        int z=1;
        int counter=0;
        while(z==1)
        {
            if((y%2)==0 && y>1)
            {
                y=y/2;
            }
            else
            {
                if((y%2)!=0 && y>1)
                {
                    y=(3*y)+1;
                }
                else
                {
                    z=2;
                }
            }
            counter++;
            counter_array[array_key]={counter};
            array_key++;
        }
    }
    int temp=0;
    int pos=0;
    for(int i=0; i<1000000;i++)
    {
        if(counter_array[i]>temp)
        {
            temp=counter_array[i];
            pos=i;
        }
    }
    cout << pos << "----->"<<temp << endl;
}

I don't know what went wrong. Please forgive me for my mistakes I'm really new at this .

RichardPlunkett

your going out of bounds by 1 on your array, but i doubt that the real issue, I think this line is the problem:

int counter_array[1000000];

Many system wont let you allocated an array on the stack like that.

ok, you have a second major problem with:

    counter_array[array_key]=   counter;
    array_key++;

given it places in the inner loop, arraykey will get incremented many times per iteration of the for loop, and will thus exceed the size of the array easily.

I am guessing here, but move the array decl into global space. Then move the above two lines to after the while loop (which will be safer, but may not do what you want I haven't checked).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related