-1
int getCycleLen(int n){//counts the number of iterations before n=1
    int cycle_len=0;
    while(n!=1){
        if(n%2==0) n/=2; else n=3*n+1;
        cycle_len++;
    }
    return cycle_len;
}
int main(){
    int i,j,n;
    int max_len=0,len;
    i = 1; j = 1000000;//j = a million
    for(n=i;n<=j;n++){
        printf("%d ",n);
        len = getCycleLen(n);
        if(len > max_len)
            max_len=len;
    }
    printf("%d %d %d\n",i,j,max_len);
}

I am using Ubuntu 16.04 and compiling using gcc 5.4. For some reason the program hangs when n of the for loop is 113299. Any suggestions as to why this happens?

jjal
  • 1
  • 1
  • 1
    Possible duplicate of [Project Euler Question 14 (Collatz Problem)](https://stackoverflow.com/questions/2643260/project-euler-question-14-collatz-problem) – EsmaeelE Aug 29 '17 at 01:32
  • Same as [collatz-sequence.c ](https://gist.github.com/rustyconover/0319ee8d6841b8d5ef39) – EsmaeelE Aug 29 '17 at 01:36

2 Answers2

3

This is an integer overflow. Use a long for the parameter to getCycleLen instead.

You can see this for yourself if you print every value of n as you iterate in getCycleLen. When the number gets too big to fit in an int, it will overflow and become a negative number. The negative numbers will then not converge on 1.

user94559
  • 59,196
  • 6
  • 103
  • 103
0

In C, integers have a specific limit. This limit depends on the architecture of your system. But basically your value has overflowed the the max possible value stored at an integer.

glyif
  • 107
  • 1
  • 6