为什么这个简单的C程序挂起?

时间:2017-08-29 01:19:59

标签: c hang

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);
}

我正在使用Ubuntu 16.04并使用gcc 5.4进行编译。出于某种原因,当for循环的n为113299时程序挂起。有关为什么会发生这种情况的任何建议吗?

2 个答案:

答案 0 :(得分:3)

这是一个整数溢出。使用$output = $this->renderPhpFile($viewFile, $params); 代替参数long

如果您在getCycleLen中进行迭代时打印n的每个值,则可以自行查看。当数字太大而无法放入getCycleLen时,它会溢出并成为负数。负数将不会收敛于1。

答案 1 :(得分:0)

在C中,整数具有特定限制。此限制取决于系统的体系结构。但基本上你的值已溢出存储在整数的最大可能值。

相关问题