1. 程式人生 > >#141-(EZOI高精度練習)[高精度]n!的精確值

#141-(EZOI高精度練習)[高精度]n!的精確值

Description

輸入 n,輸出 n! 的精確值,n!=1×2×3×…×n,1<n<1000。

Sample Input

100

Sample Output

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

直接高精度,四位佔一個int.

#include <iostream>

#define SIZE 1010

using namespace std;

int a[SIZE] = {0, 1};

int main(void)
{
	int n, len = 1, i, j;
	
	scanf("%d", &n);
	
	for (i = 1; i <= n; ++i)
	{
		for (j = 1; j <= len; ++j)
		{
			a[j] *= i; // 按位乘法
		}
		for (j = 1; j <= len; ++j)
		{
			if (a[j] > 9999) // 處理進位
			{
				a[j+1] += a[j] / 10000; // 四位佔一個int
				a[j] %= 10000;
			}
		}
		if (a[len+1])
		{
			++len;
		}
	}
	
	printf("%d", a[len]);
	for (i = len - 1; i; --i)
	{
		printf("%04d", a[i]); // 按位輸出
	}
	
	return 0;
}