1039: The 3n + 1 problem
Consider the following algorithm to generate a sequence of numbers. Start with an integer n. If n is even, divide by 2. If n is odd, multiply by 3 and add 1. Repeat this process with the new value of n, terminating when n = 1. For example, the following sequence of numbers will be generated for n = 22: 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 It is conjectured (but not yet proven) that this algorithm will terminate at n = 1 for every integer n. Still, the conjecture holds for all integers up to at least 1, 000, 000. For an input n, the cycle-length of n is the number of numbers generated up to and including the 1. In the example above, the cycle length of 22 is 16. Given any two numbers i and j, you are to determine the maximum cycle length over all numbers between i and j, including both endpoints.
输入
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0.
输出
For each pair of input integers i and j, output i, j in the same order in which they appeared in the input and then the maximum cycle length for integers between and including i and j. These three numbers should be separated by one space, with all three numbers on one line and with one line of output for each line of input.
样例输入
1 10
100 200
201 210
900 1000
样例输出
1 10 20
100 200 125
201 210 89
900 1000 174
提示
杭电1032
翻译
请考虑以下算法生成一系列数字。从整数 n 开始。如果 n 是均匀,则除以 2。如果 n 为奇数,则乘以 3 并添加 1。使用新值 n 重复此过程,在 n = 1 时终止。例如,将为 n = 22 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 生成以下数字序列,推测(但尚未证明),此算法将在每个整数 n 处以 n = 1 终止。尽管如此,这个猜想仍然保留着所有整数,最多达1000,000个。对于输入 n,n 的周期长度是生成到(包括 1)的数字数。在上面的示例中,周期长度为 22 为 16。给定任何两个数字 i 和 j,您需要确定 i 和 j 之间的所有数字(包括两个端点)的最大周期长度。
输入
输入将由一系列整数 i 和 j 组成,每行一对整数。所有整数将小于 1,000,000,大于 0。
输出
对于每对输入整数 i 和 j,输出 i、j 的顺序与它们在输入中出现的顺序相同,然后是 i 和 j 之间的整数的最大周期长度。这三个数字应用一个空格分隔,所有三个数字都放在一行上,每行输入有一行输出。
样例输入
1 10
100 200
201 210
900 1000
样例输出
1 10 20
100 200 125
201 210 89
900 1000 174
2.代码
#include<stdio.h>
#include<math.h>
int main()
{
int hs(int x);
int n,m,i,j,s,t,a,b;
while(scanf("%d %d",&n,&m)!=EOF)
{
a=n,b=m;
if(n>m)
{
t=n;
n=m;
m=t;
}
int max=0;
for(i=n; i<=m; i++)
{
s=hs(i);
max=s>max?s:max;
}
printf("%d %d %d\n",a,b,max+1);
}
return 0;
}
int hs(int x)
{
int s=0;
while(x!=1)
{
if(x%2==0)
{
x=x/2;
s++;
}
else
{
x=x*3+1;
s++;
}
}
return s;
}
364

被折叠的 条评论
为什么被折叠?



