UVa 623 500! (高精度阶乘)

来源:互联网 发布:fifo置换算法 编辑:程序博客网 时间:2024/06/08 01:03

623 - 500!

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=564

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 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 

103050100

Sample Output 

10!362880030!26525285981219105863630848000000050!30414093201713378043612608166064768844377641568960512000000000000100!93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

完整代码:

/*0.172s*/#include<cstdio>int factorial[1001][2800];int main(void){int i, j, n;factorial[0][0] = 1;factorial[1][0] = 1;for (i = 2; i < 1001; i++)for (j = 0; j < 2800; j++){factorial[i][j] += factorial[i - 1][j] * i;if (factorial[i][j] > 9){factorial[i][j + 1] = factorial[i][j] / 10;factorial[i][j] %= 10;}}while (~scanf("%d", &n)){printf("%d!\n", n);for (i = 2600; i > 0; i--)if (factorial[n][i])break;for (; i >= 0; i--)printf("%d", factorial[n][i]);putchar('\n');}return 0;}


/*1.238s*/import java.io.*;import java.util.*;import java.math.*;public class Main {static final int maxn = 1001;static Scanner cin = new Scanner(new BufferedInputStream(System.in));public static void main(String[] args) {BigInteger[] f = new BigInteger[maxn];f[0] = BigInteger.ONE;for (int i = 1; i < maxn; ++i)f[i] = f[i - 1].multiply(BigInteger.valueOf(i));while (cin.hasNextInt()) {int n = cin.nextInt();System.out.println(n + "!");System.out.println(f[n]);}}}


原创粉丝点击