General

3n+1문제 (The 3n+1 Problem)

일등하이 2013. 6. 19. 20:32
반응형







using System;

namespace Chapter_01_Q1
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            string str = Console.ReadLine ();
            string[] arr = str.Split (new char[]{' '});

            Q1 q1 = new Q1 ();
            int a = System.Int32.Parse (arr[0]);
            int b = System.Int32.Parse (arr[1]);
            q1.Init (a, b);
        }
    }

    class Q1 {
        long lbound, ubound, lbOrg, ubOrg, temp;
        long i, j, length, max_length;

        public Q1()
        {

        }

        public void Init(int a, int b){

            lbound = lbOrg = a;
            ubound = ubOrg = b;

            if( lbound > ubound ){
                temp = lbound;
                lbound = ubound;
                ubound = temp;
            }
            max_length = 0;

            for(i = lbound; i<= ubound; i++){
                j = i;
                length = 1;

                while (j!=1) {

                    if( (j & 1) != 0){
                        j = j * 3 + 1;    //(3n+1)
                        length++;
                    }
                    while ((j&1) == 0) {
                        j = j>>1; //(n /2)
                        length++;
                    }
                }

                if (length > max_length)
                    max_length = length;
            }

            Console.WriteLine (lbOrg + "," +  ubOrg + "," + max_length);
        }
    }
}



반응형