I am using VC++ 2010. I have written a short program to get Collatz conjecture chain for 1 million numbers in an long int array and get the highest number in series. When I try to run the code, I get stack overflow exception.
How should I get past this?
//Might have took un-needed headers
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "iostream"
#include "fstream"
#include "string"
#include "list"
using namespace std;
//traverse the array for max term
long int max_array(long int a[], long int num_elements)
{
long int i, max=-32000;
for (i=0; i<num_elements; i++)
{
if (a[i]>max)
{
max=a[i];
}
}
return(max);
}
//recursive function to calculate and count based on Collatz_conjecture
long int Collatz( long int c1, long int currentcounter)
{
if ( c1 == 1) return currentcounter;
if ( c1 % 2 ==0)
{
currentcounter++;
Collatz (c1/2, currentcounter);
}
else
{
currentcounter++;
Collatz((3*c1)+1, currentcounter);
}
}
void main()
{
long int totalcounter[1000000]={0},t1,max;
for (long int i=1;i<1000001;i++)
{
totalcounter[i]++;
totalcounter[i]=Collatz(i,totalcounter[i]);
printf("Collatz count of no: %li is %li \n",i,totalcounter[i]);
}
max = max_array(totalcounter, 1000000);
printf("The max is %d\n", max);
}