Q100: The 3n + 1 problem
不知道是不是太久沒寫C++了
寫起來卡卡的
於是我就先從ACM的題目下手
翻了翻我Gmail信箱,竟然翻到了一封"化石"!
那是我高一開是玩ACM寫的
最簡單的: Q100: The 3n + 1 problem
看了突然覺得那時候用ANSI C寫的有夠爛~所以我就重新寫了一次
這次是用C++
po給大家對照一下吧
這是高一寫的(with C)
這是我昨天寫的(with C++)
寫起來卡卡的
於是我就先從ACM的題目下手
翻了翻我Gmail信箱,竟然翻到了一封"化石"!
那是我高一開是玩ACM寫的
最簡單的: Q100: The 3n + 1 problem
看了突然覺得那時候用ANSI C寫的有夠爛~所以我就重新寫了一次
這次是用C++
po給大家對照一下吧
這是高一寫的(with C)
#include <stdio.h> //2006/8/10
int main(void)
{
long int i, t, bg, a, b, c;
char ch;
bg = 0;
while (scanf("%d%d", &a, &b) == 2)
{
if (a > b)
{
t = a;
a = b;
b = t;
}
for(i = a; i <= b; i++)
{
t = i;
c = 1;
while (t != 1)
{
if (t % 2 == 1)
t = t * 3 +1;
else
t /= 2;
c++;
}
if (c > bg)
bg = c;
}
printf("%d %d %d", a, b, bg);
}
}
這是我昨天寫的(with C++)
//Q100 The 3n + 1 problem
//Accepted 2008-04-12
#include <iostream>
using namespace std;
int circlelength(unsigned long int);
int main(void)
{
int i, j, k, temp, bg = 0;
while(cin >> i >> j)
{
cout << i << " " << j;
if (i > j)
{
temp = i;
i = j;
j = temp;
}
for(k = i; k <= j; k++)
if (circlelength(k) > bg)
bg = circlelength(k);
cout << " " << bg << endl;
bg = 0;
}
}
int circlelength(unsigned long int n)
{
int times = 1;
while(n != 1)
{
if (n%2 == 0)
n /= 2;
else
n = n * 3 + 1;
times++;
}
return times;
}
留言