2017-08-29 71 views
-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); 
} 

我使用Ubuntu 16.04並使用gcc 5.4編譯。出於某種原因,當for循環的n爲113299時,程序掛起。對此有何建議?爲什麼這個簡單的C程序掛斷?

+1

[Project Euler Question 14(Collat​​z Problem)](https://stackoverflow.com/questions/2643260/project-euler-question-14-collat​​z-problem) – EsmaeelE

+0

與[collat​​z-sequence.c相同 ](https://gist.github.com/rustyconover/0319ee8d6841b8d5ef39) – EsmaeelE

回答

3

這是一個整數溢出。改爲使用long代替參數getCycleLen

如果您在getCycleLen中迭代時打印每個值n,您可以自己查看。當數字變得太大而不適合int時,它會溢出併成爲負數。負數將不會收斂於1.

0

在C中,整數有一個特定的限制。此限制取決於系統的體系結構。但基本上你的價值溢出了以整數存儲的最大可能值。

相關問題