3n+1 数字处理

来源:互联网 发布:js undefend 判断 编辑:程序博客网 时间:2024/05/17 22:24

题目链接:http://acm.pdsu.edu.cn/problem.php?id=1039

题目描述

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

题意
输入n和m,把从n到m的任意一个数进行判断,偶数则除以2,奇数则乘3加1,一直到结果是1结束,然后将输入的m,n按原顺序,还有处理的最多的次数,三个数中间含有空格地进行输出,每行输出占一行。

解体思路:
用for循环,然后进行处理,将每一次处理的次数存进数组,通过比较求出最多的次数;
错误1次,应按原输入顺序来输出n,m,我只是按从小到大输出,故错误;
用一变量来观察是否进行交换过值,若交换过,则反序输出。

代码示例:
#include<stdio.h>
int main()
{
    int n,max,b,i,j,t,m,y,x,a[10000];
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        b=0;
        if(n>m)//判断大小,并把小值放在后边,且b来判断是否交换值;
        {
            t=n;n=m;m=t;
            b++;
        }
        i=0,max=0,j=0;
        for(x=n;x<=m;x++)
        {
            i=1,y=x;
            while(y!=1)//到1停止循环;
            {
                if(y%2==0)
                    y/=2;
                else
                    y=y*3+1;
                i++;//循环处理的次数;
            }
            a[j]=i;//将次数赋进数组里面;
            j++;
        }
        for(i=0;i<j;i++)
        {
            if(a[i]>max)
                max=a[i];
        }
        if(b==1)//若交换过,则反序输出;
        {
            printf("%d %d %d\n",m,n,max);
        }else
        printf("%d %d %d\n",n,m,max);
    }
    return 0;
}

阅读全文
0 0
原创粉丝点击