UVA 694 - The Collatz Sequence
2013-01-25 19:12
302 查看
刚开始,根据题意,
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,limit都为int类型,提交返TLE。
后来改a为long类型的,(limit可以是int),提交AC
一想是不是a在运算的过程中,会有超出int范围的时候?
但是limit是int类型的,a每次运算完,不都要和limit做比较么?如果大于limit,就break了,哪还有机会超出int范围呢?纳闷~
另外,做此题的时候,也学到了用freopen("input.txt", "r", stdin); 输入流读取样例数据的时候,如果不重定向输出到文档,而是照旧输出到控制台,为避免出现运行窗口一闪而过的情况,需要在return 0; 的前面加一句: freopen("CON", "r", stdin);
交题的时候,把freopen(); 相关的都注释掉。
详细参看:用freopen()读取程序的测试数据 (http://blog.csdn.net/arcsinsin/article/details/8543260)
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,limit都为int类型,提交返TLE。
后来改a为long类型的,(limit可以是int),提交AC
一想是不是a在运算的过程中,会有超出int范围的时候?
但是limit是int类型的,a每次运算完,不都要和limit做比较么?如果大于limit,就break了,哪还有机会超出int范围呢?纳闷~
另外,做此题的时候,也学到了用freopen("input.txt", "r", stdin); 输入流读取样例数据的时候,如果不重定向输出到文档,而是照旧输出到控制台,为避免出现运行窗口一闪而过的情况,需要在return 0; 的前面加一句: freopen("CON", "r", stdin);
交题的时候,把freopen(); 相关的都注释掉。
详细参看:用freopen()读取程序的测试数据 (http://blog.csdn.net/arcsinsin/article/details/8543260)
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> using namespace std; int main() { int limit, num, aa, k = 0; long a; //a声明为int会TLE /*#ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif*/ freopen("input.txt", "r", stdin); while (scanf("%ld%d",&a, &limit) == 2) { if (a < 0 && limit < 0)break; num = 1; k++; aa = a; while (a != 1) { num++; if (a % 2 == 0) { a /= 2; if (a > limit) { num--; break; } } else { a = 3 * a + 1; if (a > limit) { num--; break; } } } printf("Case %d: A = %ld, limit = %d, number of terms = %d\n",k,aa,limit,num); } freopen("CON", "r", stdin);//如果不想输入或输出到文件了,要恢复句柄 system("pause"); return 0; }
相关文章推荐
- uva694 The Collatz Sequence
- UVa_694 - The Collatz Sequence
- UVa 694 - The Collatz Sequence
- uva694 The Collatz Sequence
- UVA 694 - The Collatz Sequence
- UVa694 - The Collatz Sequence(模拟)
- UVa 694 The Collatz Sequence(序列)
- UVa 694 - The Collatz Sequence
- uva-694 - The Collatz Sequence
- UVA 694 - The Collatz Sequence
- uva694 The Collatz Sequence
- UVA 694-The Collatz Sequence
- uva 694 - The Collatz Sequence
- 694 - The Collatz Sequence---关于goto语句的一些反思(还有uva的Runtime Error问题的解决)
- UVA 694-The Collatz Sequence
- UVa 694 - The Collatz Sequence
- UVA694 UVALive5466 The Collatz Sequence【模拟】
- 【UVA】【第0章】694 - The Collatz Sequence
- UVa 694 The Collatz Sequence (数论)
- UVa 694 The Collatz Sequence