题意:
输入两个数 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.题目:
代码:
# include# include # include 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