In these days you can more and more often happen to see programs which perform some useful calculations being executed rather then trivial screen savers. Some of them check the system message queue and in case of finding it empty (for examples somebody is editing a file and stays idle for some time) execute its own algorithm.
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 not 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.
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!.
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).
• Mind that visually big number of case 4 is broken after 80 characters, but this is not the case in the real output file.
Sample Input
10
30
50
100
Sample Output
10!
3628800
30!
265252859812191058636308480000000
50!
30414093201713378043612608166064768844377641568960512000000000000
100!
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
问题链接:UVA623 500!
问题简述:(略)
问题分析:
大数计算问题用模拟来解决。通常用字符表示10进制的1位,然而算得不会太慢了?
这里的解法采用百万进制和10^15进制,算得要快许多!
现在计算机已经是64位了,用long long类型应该算得更快。
程序说明:(略)
题记:(略)
AC的C++语言程序如下:
/* UVA623 500! */
#include <bits/stdc++.h>
#define CHOICE
using namespace std;
#ifdef CHOICE
typedef int INT;
const INT BASE = 1000000;
const int N = 1000;
#else
typedef unsigned long long INT;
const INT BASE = 1e15;
const int N = 400;
#endif
INT digits[N];
int main()
{
int n;
while(scanf("%d", &n) != EOF) {
memset(digits, 0, sizeof(digits));
digits[0] = 1;
int len = 1;
for(int i = 2; i <= n; i++) {
INT carry = 0;
for(int j = 0; j < len; j++) {
digits[j] = digits[j] * i + carry;
carry = digits[j] / BASE;
digits[j] %= BASE;
}
if(carry)
digits[len++] = carry;
}
printf("%d!\n", n);
#ifdef CHOICE
printf("%d", digits[len - 1]);
#else
printf("%lld", digits[len - 1]);
#endif
for(int i = len - 2; i >= 0; i--)
#ifdef CHOICE
printf("%06d", digits[i]);
#else
printf("%015lld", digits[i]);
#endif
printf("\n");
}
return 0;
}