694 - The Collatz Sequence

题意:
输入两个数 A 和 L, 按以下条件进行循环运算, 问最后结束循环时一共进行了多少次运算?
1. 若 A 为 1 或 A > L, 则退出.
2. 若 A 为偶数, 则 A = A/2.
3. 若 A 为奇数, 则 A = 3*A + 1.

思路:
题目所给思路已经很清楚了.

要点:
1. 题目虽然说明输入最大的 A 和 L 不会超出 32 bit 所能表示的最大整数(2,147,483,647), 但是在计算是, 3*A + 1 很有可能会超出这个最大的整数, 数据溢出, 导致 Time limit exceeded; 所以 A 和 L 的类型都应定义为 long.
2. 因为这里的写法是把 A==1 写到 while 判断条件里去了, 所以最后如果是在 A==1 时退出循环的, 则 terms 需要加 1.

题目:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=94&page=show_problem&problem=635

代码:

# include <iostream>
# include <string>
# include <cstdio>
using namespace std;

int main(int argc, char const *argv[])
{
	#ifndef ONLINE_JUDGE
		freopen ("694_i.txt", "r", stdin);  
		freopen ("694_o.txt", "w", stdout); 
	#endif
	
	// 这里类型 使用 int 的话, 会报 Time limit exceeded
	// 因为 3*A + 1 很有可能会导致 int 溢出, 从而永远算不完
	long A;
	long L;
	cin >> A >> L;

	int cs = 0;	// case 数目
	while(A > 0 && L > 0){
		++ cs;
		cout << "Case " << cs << ": A = " << A << ", limit = " << L << ", number of terms = ";

		int terms = 0;
		while(A != 1 && A<=L){

			if(A % 2 == 0){
				A = A/2;
			}else{
				A = 3*A + 1;
			}
			++ terms;
		}
		// 如果最后是因为 A=1 退出的, 则 terms 要加1
		cout << (A==1 ? ++terms : terms) << endl;

		cin >> A >> L;
	}
	
	return 0;
}


环境:C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE

转载于:https://my.oschina.net/zenglingfan/blog/137799

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值