본문 바로가기

공부/컴퓨터

[알고리즘] 3n+1 문제

반응형
#include <iostream.h>
#define MAX 100001

        unsigned long sts[MAX] = { 0 , };

int main()
{
    unsigned long i,j,max;
    register unsigned long cnt,tmax,temp;
    sts[1] = 1;


    while ( cin >> i >> j )
    {
        max ^= max;

        cout << i << " " << j << " ";
        if ( i > j ) {
                int temp = i;
                i = j;
                j = temp;
        }

        for ( cnt = i ; cnt <= j ; cnt++ )
        {
                        tmax ^= tmax;
                        temp = cnt;
            while( true )
            {
                                if ( temp < MAX && (sts[temp]) ) {
                                        tmax += (sts[temp]-1) ;
                                        break;
                                }

                temp = ( temp & 1 ) ? (temp *3 + 1) : ( temp >> 1 );
                tmax++;

            }
            tmax++;

            if ( cnt < MAX ) sts[cnt] = tmax;

            if ( max < tmax )  max = tmax;

        }
        cout << max << endl;
     }

}
반응형