问题链接:UVA100 POJ1207 HDU1032 The 3n + 1 problem。
问题描述:参见上述链接。
问题分析:根据给定的算法计算整数循环到1的次数,可以用一个函数来实现,可以使用记忆存储来加快计算速度。
程序说明:数组cs[]用于存储已经算过的次数,极大地加快了计算速度。程序中,统计函数cscount()是用递归实现的,如果用递推实现,速度会更快。
AC的C++语言程序如下:
/* UVA100 POJ1207 HDU1032 The 3n + 1 problem */
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1000000;
int cs[MAXN+1];
// Collatz sequence count
int cscount(int x)
{
if(x <= MAXN && cs[x])
return cs[x];
int count;
if(x % 2 == 0)
count = 1 + cscount(x / 2);
else
count = 1 + cscount(x * 3 + 1);
if(x <= MAXN)
cs[x] = count;
return count;
}
int main()
{
int a, b, max, temp;
memset(cs, 0, sizeof(cs));
cs[1] = 1;
while(cin >> a >> b) {
cout << a << " " << b << " ";
if(a > b) {
temp = a;
a = b;
b = temp;
}
max = 0;
for(int i=a; i<=b; i++) {
temp = cscount(i);
if(temp > max)
max = temp;
}
cout << max << endl;
}
return 0;
}