您的位置:首页 > 其它

1039: The 3n + 1 problem (附:题意解读+防“坑”注释)

2018-01-12 20:04 387 查看

题目描述

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是偶数,那么把它乘以2(即n=2×n)。如果n是奇数,那么把它乘以三之后再加一(即n=n×3+1)。重复这一过程直到n等于1时停止。举个例子,对于n=22来说,它将经历以下过程:22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1。猜测(但未证实)所有的整数经过这种运算之后都有等于1的时候。然而,我们对于最少到1,
000, 000的整数来说都能保证通过这种运算之后变成1。在上述例子中,22的所经历的过程长度是16。任给两个数字i和j,你需要计算出[i,j]区间中的所有的数字的过程长度,并找出过程长度最大的那个数字的过程长度。

这道题即使看懂了题意,如果稍不注意,也是做不对的。题中的两个“坑”我在代码中会做注释。

代码示例:
#include<stdio.h>

int main()

{

    int i,j,t,n,flag,flag_max;

    while(~scanf("%d%d",&i,&j))

    {

        printf("%d %d",i,j);

        if(i>j)//因为我们不知道i和j的大小关系(题目没说),因此必须做下转换。

        {

            t=i;

            i=j;

            j=t;

        }

        flag_max=0;

        for(;i<=j;i++)

        {

            n=i;

            flag=1;//注意flag要从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

            //注意对于22来说,是从它本身22就算一次的,然后每做一次运算也算一次

            while(n!=1)

            {

                if(n%2)

                    n=3*n+1,flag++;

                else

                    n=n/2,flag++;

            }

            flag_max=flag_max>=flag?flag_max:flag;

        }

        printf(" %d\n",flag_max);

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: