题目很简单,但是一开始却得到了Time Limit的结果,让人感到很诧异。仔细阅读发现,题目中有一个说明:
Neither of these, A or L, is larger than 2,147,483,647 (the largest value that can be stored in a 32-bit signed integer).
所以应该是A溢出造成了程序“死循环”,最终导致超时。
-------------------------------------------------------------
将A由int改为long long后即正确。其中cin,cout默认支持long long。
1 #include <iostream> 2 using namespace std; 3 int main() 4 { 5 long long a, lim,a_store; 6 int count; 7 int casenum=0; 8 //cin >> a>>lim; 9 //while (a>=0||lim>=0) 10 while (cin >> a >> lim) 11 { 12 casenum++; 13 a_store = a; 14 count = 1; 15 if (a < 0 && lim < 0) 16 return 0; 17 while (a != 1 && a <= lim) 18 { 19 if (a % 2) 20 { 21 a = a * 3 + 1; 22 } 23 else 24 { 25 a = a / 2; 26 } 27 count++; 28 } 29 if (a > lim) 30 count--; 31 32 cout <<"Case "<< casenum<<": A = " << a_store << ", limit = " << lim << ", number of terms = " << count<<endl; 33 } 34 return 0; 35 }
UVaOJ 694 - The Collatz Sequence
时间: 2024-10-13 17:30:12