1. 程式人生 > >N!(高精度)

N!(高精度)

問題描述:

Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!

    input:

One N in one line, process to the end of file.

    output:

For each N, output N! in one line.

問題分析:這道題典型的是一道大數模板的應用。建立兩個陣列a[i],b[j],陣列的每一個元素儲存一個四位數,升位用一個變數up表示。結果先表示為一個臨時變數,最後儲存到res[i+j]陣列中。

計算公式如下:

temp= a[i]*b[j]+res[i+j]+up;

AC程式碼:

// N!
#include<iostream>
using namespace std;
#include <cstring>
#define N 10003
int main()
{
	ios::sync_with_stdio(false);
	int n;
	int a[N];
	//len1表示位數 
	int i,j,up,len1;
	
	while(cin>>n){
		len1 = 0;
		a[0] = 1;
		for(i = 1;i <= n;i++){
			up = 0;
			for(j = 0;j <= len1;j++){
				a[j] = a[j]*i+up;
				up = a[j] / 10000; 
				a[j] %= 10000;
			}
			if(up > 0){
				len1++;
				a[len1] = up;
			}
		}
		cout<<a[len1];
		for(i = len1-1;i >= 0;i--){
			cout.width(4);
			cout.fill('0');
			cout<<a[i];
		}
		cout<<endl;
	}
	return 0;
}