2007년 03월 19일
[code] 3n+1 (The 3n+1 Problem)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
unsigned int min;
unsigned int max;
}VAULE;
unsigned int Get_Value(unsigned int value, unsigned int nCount);
int main(int argc, char* argv[])
{
unsigned int index = 0;
unsigned int max_count = 0;
unsigned int tmp_count = 0;
FILE* pInput_File = fopen("input.txt", "rt");
FILE* pOutput_File = fopen("output.txt", "wt");
VAULE value = {0};
if( pInput_File == NULL || pOutput_File == NULL )
{
printf("File Open Error!\n");
exit(1);
}
while( !feof(pInput_File) )
{
fscanf(pInput_File, "%d %d", &(value.min), &(value.max));
for( index = value.min ; index <= value.max ; index++ )
{
tmp_count = Get_Value(index, 1);
if( max_count < tmp_count )
{
max_count = tmp_count;
}
}// for
printf("min: %d max: %d count: %d\n", value.min, value.max, max_count);
fprintf(pOutput_File, "%d %d %d\n", value.min, value.max, max_count);
max_count = tmp_count = 0;
}// while
fclose(pInput_File);
fclose(pOutput_File);
return 0;
}
unsigned int Get_Value(unsigned int value, unsigned int nCount)
{
if( value == 1 ) // 정수 n 이 아래와 같은 알고리즘으로 했을 경우
{ // 결과적으로 1로 변한다는 것을 이용
return nCount;
}
else
{
value = (value % 2 == 0) ? (value / 2) : (value * 3) + 1
/*
if( (value % 2) == 0 )
{
value /= 2;
}
else
{
value = (value * 3) + 1;
}
*/
nCount++;
Get_Value(value, nCount);
}
}
알고리즘의 간단한 문제...
입력된 두 수의 사이의 한 정수에 대해서 짝수일 경우 /2, 홀수일 경우 3을 곱한후 1을 더한다
이것의 결과로 Count가 많은 것을 찾아내는 것이다
예> 1 20 20 (정수1, 정수2, 최대 Count)
두수 사이의 최대 Count를 알아내는 것은 재귀함수를 이용해서 찾아내었다.
# by | 2007/03/19 12:31 | ┣ Algorithm | 트랙백 | 덧글(3)





☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]