HDU 1032 The 3n + 1 problem

17 篇文章 1 订阅
/*
2015年2月26日14:46:01
思路很容易想到:
第一步:求每个数的Cycle
第二步:用当前的Cycle和maxCycle比较
有些细节要注意:
(1)、小心使用全局变量,不然会出现累加效果
(2)、每次输入一组数据后记得要把maxCycle清零

*/
# include <stdio.h>
//int maxCycle = 0; //谨慎使用全局变量,很容出错
int countCycle(int n,int count)
{
	if(n == 1) 
	{
		count++;
		return count;
	}
	if((n % 2) != 0) 
	{
		n = 3*n + 1;
		count++;
		countCycle(n,count);
	}
	else
	{
		n = n/2;
		count++;
		countCycle(n,count);	
	}
}

/*void max(int cycle)
{
	if(maxCycle < cycle)
		maxCycle = cycle;
}*/

int main(void)
{
	int i,j;
	while(scanf("%d %d",&i, &j)!=EOF)
	{ 
		int currentCycle;
		int maxCycle;
		int temp = 0;
		getchar();    //吸收回车符。
		if((i <= 0) && (j <= 0))break;
		while((j - i) >= 0)
		{
			currentCycle = countCycle(i,temp);
			//max(currentCycle);
			if(maxCycle < currentCycle)
			{
				maxCycle = currentCycle;
			}
			i++;
		}
		printf("%d\n",maxCycle);
		maxCycle = 0; 
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值