U E D R , A S I H C RSS

3n 1/이도현

2005-12-30 14:39:20 Accepted 3.256 436 56031 C++ 100 - The 3n + 1 problem

Accepted .
. 하 한 테 .

1. 2 . ( )
2. . (& ), 2(right shift 1) - .
3. 확한 파 . - .
4. - .

~cpp
// The 3n + 1 problem
// UVa ID : 100
#include <iostream>
using namespace std;
int cycle_length(int input);

int main()
{
	int input1, input2;

	while (cin >> input1 >> input2)
	{
		int i;
		int max_count = -1;
		int temp = 0;
		
		//     !!
		cout << input1 << " " << input2 << " ";

		//       (for  )
		if (input1 > input2)
		{
			int swap = input1;
			input1 = input2;
			input2 = swap;
		}

		for (i = input1; i <= input2; i++)
		{
			temp = cycle_length(i);				// cycle legnth 
			if (temp > max_count)
				max_count = temp;				// 큰  max_count
		}
		cout << max_count << endl;
	}

	return 0;
}

// cycle length 
int cycle_length(int input)
{
	int argument = input;		//    
	int count = 0;				// 
	
	while (true)
	{
		//  
		if (argument == 1)
		{
			count++;
			break;
		}

		// LSB 0 , 1 .
		if ((argument & 1) == 0)
		{
			//  2 right shift  .
			argument >>= 1;
			count++;
		}
		else
		{
			//     .
			argument = 3 * argument + 1;
			argument >>= 1;
			count += 2;
		}
	}

	return count;
}

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:22:17
Processing time 0.0109 sec