The 3n+1 Problem

题目描述:
这是一个古老的猜想:给定任何一个正整数n,对它进行以下操作:
n是偶数:n=n/2
n是奇数:n=3*n+1
这样经过多步操作后,最后必定变为1
如对13进行操作: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
一共经历了9次操作,则称13这个数的周期是9

输入:
多组测试数据,每组一行,一行里有两个数m和n,
请你找出m和n之间(包括m,n)的周期最大的数的周期
其中m,n均为小于或者等于2e6的正整数

输出:
m,n之间周期最大的数的周期,一个结果单独占一行

样例输入:
1 10
2 3
30 100

样例输出:
19
7
118

#include 

int times;
void cycle(int n)
{
	times++;
	if (n%2==0)
		n = n/2;
	else
		n = 3*n+1;
	if (n!=1)
		cycle(n);
}
int get_cycle(int n) {
	times=0;
	cycle(n);
	return times;
}
int get_max_cycle(int n1,int n2)
{
	int i,ret=0,max=0;
	for(i=n1; imax)
			max=ret;
	}
	return max;
}
int main(void)
{
	int n1,n2;
	while(scanf("%d%d", &n1, &n2) != EOF)
		printf("%dn", get_max_cycle(n1,n2));
	return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.