【C语言】The 3n + 1 problem

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并包括1。在上面的示例中,循环长度22中的16是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.

输出
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.

#include<stdio.h>
int main() {
	int a,b;
	while(scanf("%d %d",&a,&b)!=EOF) 
	{
		int max=0;
		int m,n;
		if(a<b)
		{
			m=a;
			n=b;
		}
		else
		{
			m=b;
			n=a;
		}
		for(int i=m; i<=n; i++) 
		{
			int j=i,sum=1;
			while(j!=1) 
			{
				if(j%2==0) 
				{
					j=j/2;
				} else 
				{
					j=j*3+1;
				}
				sum++;
			}
			if(max<sum) 
			{
				max=sum;
			}
		}
		printf("%d %d %d\n",a,b,max);
	}
}
发布了24 篇原创文章 · 获赞 16 · 访问量 1216

猜你喜欢

转载自blog.csdn.net/weixin_46014378/article/details/104454570