UVA OJ 623 500!
2014-11-25 19:54
169 查看
500! |
As an examples we can give programs which calculate primary numbers.
One can also imagine a program which calculates a factorial of given numbers. In this case it is the time complexity of order O(n) which makes troubles, but the memory requirements. Considering the fact that 500! gives 1135-digit number no standard, neither integer nor floating, data type is applicable here.
Your task is to write a programs which calculates a factorial of a given number.
Assumptions: Value of a number ``n" which factorial should be calculated of does not exceed 1000 (although 500! is the name of the problem, 500! is a small limit).
Input
Any number of lines, each containing value ``n" for which you should provide value of n!Output
2 lines for each input case. First should contain value ``n" followed by character `!'. The second should contain calculated value n!.Sample Input
10 30 50 100
Sample Output
10! 3628800 30! 265252859812191058636308480000000 50! 30414093201713378043612608166064768844377641568960512000000000000 100! 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
算法竞赛入门经典上的解法如下:会超时。
#include <cstdio> #include <cstring> using namespace std; const int maxn = 3000; int a[maxn]; int main() { int n; int i, j; int c, s; while (scanf("%d", &n) == 1) { memset(a,0,sizeof(a)); a[0] = 1; for (i = 2; i <= n; i++) { c = 0; for (j = 0; j < maxn; j++) { s = a[j] * i + c; a[j] = s % 10; c = s/10; } } for (i = maxn; i >= 0;i--) if (a[i]) break; printf("%d!\n",n); for (j = i; j >= 0; j--) printf("%d",a[j]); printf("\n"); } return 0; }
修改后如下:
#include <cstdio> #include <cstring> using namespace std; const int maxn = 500; int a[maxn]; int main() { int n; int i, j; int len; int c, s; while (scanf("%d", &n) == 1) { memset(a, 0, sizeof(a)); a[0] = 1; len = 1; for (i = 2; i <= n; i++) { c = 0; for (j = 0; j < len; j++) { s = a[j] * i + c; a[j] = s % 1000000; c = s / 1000000; } if (c) a[len++] = c; } printf("%d!\n", n); printf("%d",a[len-1]); for (j = len-2; j >= 0; j--) printf("%06d", a[j]); printf("\n"); } return 0; }
相关文章推荐
- UVa 623 - 500!
- UVa 623 500!
- UVa 623 - 500!
- UVA 623 - 500!
- UVa 623 500! (高精度阶乘)
- 有20个数组,每个数组有500个元素,升序排列,现在在这20*500个数中找出排名前500的数。
- [Troubleshooting]-Exchange 2013 OWA & ECP 发生错误 500意外错误
- 某中国500强企业BI系统成功应用案例
- statusCode(状态码) 200、300、400、500序列
- 500 G JAVA视频网盘分享
- Too many alarms (500) registered
- TopCoder SRM687 div1 500
- 常见HTTP状态码(200、301、302、500等)解说
- spring boot 下 500 404 错误页面处理
- Eclipse运行报错:HTTP Status 500 - javax.servlet.ServletException: java.lang.UnsupportedClassVersionError
- UVA oj 494 Kindergarten Counting Game(简单字符串)
- 快上车项目简介(500字)
- HTTP Status 500 - Tag file directory /tagfiledoes not start with "/WEB-INF/tags"
- 623盐城龙卷风
- apache的错误500错误,引入jstl核心标签库遇到的问题