杭电 1032 The 3n+1问题

    这是杭电上的一道简单题,我很意外我的代码可以AC,我以为这样写会超时!
    本来是想建立一个表,通过查表的形式我觉得效率会更高一些,可是在建表的过程中,表中的数据实在难搞(也可能是我

没发现规律),建表问题暂且搁置!

 

View Code
#include <stdio.h>
#include <stdlib.h>

int counter( int n )
{
    int cnt = 1;
    while( n != 1 )
    {
           if( !(n%2) )
           {
               n = n/2;
               cnt++;
           }
           else
           {
               n = 3*n+1;
               cnt++;
           }
    }
    return cnt;
}

int main(int argc, char *argv[])
{
    int m, n, i, cnt, max ;
    while( scanf( "%d %d", &m, &n ) != EOF )
    {
           printf( "%d %d ", m, n );
           if( m > n )
           {
               m = m + n;
               n = m - n;
               m = m - n;
           }
           max = 0;
           for( i = m; i <= n; i++ )
           {
                cnt = counter(i);
                if( max < cnt )
                    max = cnt;
           }
           printf( "%d\n", max );
    }
  
  system("PAUSE");    
  return 0;
}

 

posted @ 2013-02-25 10:08  翼展zjz  阅读(125)  评论(0编辑  收藏  举报