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.
翻译:
请考虑以下算法以生成数字序列。以整数 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。尽管如此,这个猜想仍然适用于至少1, 000, 000的所有整数。对于输入 n,n 的循环长度是生成的数量,最多包括 1。在上面的示例中,循环长度 22 为 16。给定任意两个数字 i 和 j,您将确定 i 和 j 之间所有数字(包括两个端点)的最大循环长度。
输入:
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.
翻译:
输入将由一系列整数对 i 和 j 组成,每行一对整数。所有整数将小于 1,000,000 且大于 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.
输出:
对于每对输入整数 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
解析:
题目的注意点是输入的i和j即便i>j也需要按i,j输入的顺序来输出。
然后对于题目来说需要将变量定义为long long。
代码:
#include<stdio.h>
int main()
{
long long i,j,k,num,max,s,t;
while((scanf("%lld%lld",&i,&j))!=EOF)
{
printf("%lld %lld ",i,j);
if(i>j)
{
t=i;
i=j;
j=t;
}
max=1;
for(k=i;k<=j;k++)
{
num=1;
s=k;
while(s!=1)
{
if(s%2)
{
s=3*s+1;
num++;
}
else
{
s=s/2;
num++;
}
}
if(num>=max)
max=num;
}
printf("%lld\n",max);
}
return 0;
}