# 3n+1 Problem

This topic is 4324 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I was trying to solve the 3n+1 problem I am sure this code can be improved in many ways...but this is my first attempt and I will concentrate on improving on it once it starts working properly...I am getting a crash in this. plz help me find the cause??
#include <stdio.h>

void ThreeNPlusOne(unsigned ,unsigned, unsigned  [][30] ,unsigned [] );

int main(){

unsigned pairs;			 //for storing number fo pairs entered
unsigned Obuffer[30];	 //Original Data
unsigned Mbuffer[30][30];//Modified Data
unsigned CycleLength[30];
unsigned i,j;			 //counter

printf("How many pairs do you want to enter");
scanf("%u\n",&pairs);

for(i=0;i<pairs*2;++i){
scanf("%u",&Obuffer[i]);
}

/*for(i=0;i<pairs*2;++i){
printf("%u ",buffer[i]);
}*/

for(i=0;i<pairs*2;i+=2)
ThreeNPlusOne(Obuffer[i],Obuffer[i+1],Mbuffer,CycleLength);

for(i=0;i<(Obuffer[i]-Obuffer[i+1]+1);++i)
{
printf("\n");
for(j=0;j<CycleLength[i];++j)
printf("%u ",Mbuffer[i][j]);
}

return 0;
}

void ThreeNPlusOne(unsigned low,unsigned high,unsigned Mbuffer[][30],unsigned CycleLength[]){

unsigned static count1=0;
unsigned static count2=0;
while(low++<=high){
unsigned temp=low;
while(temp){

if(temp==1)
{
CycleLength[count2++]=count1;
return ;
}
else if(temp%2!=0)
{
temp=3*temp+1;
Mbuffer[count2][count1++]=temp;
}
else
{
temp/=2;
Mbuffer[count2][count1++]=temp;

}
}
}

}


##### Share on other sites
Where do you get the crash and what kind of crash? Is it an unhandled exception (what kind)?

EDIT: Your code looks like C, so it's most likely not an unhandled exception.

##### Share on other sites
Quote:
 Original post by CTarWhere do you get the crash and what kind of crash? Is it an unhandled exception (what kind)?EDIT: Your code looks like C, so it's most likely not an unhandled exception.

I entered 1 for pairs

and then 22 24

here is the screenshot of error
http://www.geocities.com/arorasp2000/Error.bmp

##### Share on other sites
Ok, I think your error is in this loop:
for(i=0;i<(Obuffer[i]-Obuffer[i+1]+1);++i){	printf("\n");	for(j=0;j<CycleLength[i];++j)		printf("%u ",Mbuffer[i][j]);}

When you entered 22 and 24 Obuffer looks like this:
Obuffer[0] = 22
Obuffer[1] = 24
Now remember i is an unsigned int so it cant use negative values. Obuffer[i]-Obuffer[i+1]+1 with i = 0 is the same as 22-24+1 which should equal -1, but since we are working with unsigned numbers it will be the greatest possible number (most likely, 4294967296). Your arrays are not big enough to let you read that much, so at some point when i becomes too great (30) you will access more values than you have allocated.