1. 程式人生 > 實用技巧 >刷題-計算階乘(大數的儲存)

刷題-計算階乘(大數的儲存)

題目來源:http://47.106.114.75/problem/558
題目描述:
Problem Description
給定一個整數N(0 ≤ N ≤ 10000),要求計算N的階乘。

Input
每個N佔一行,直到檔案尾。

Output
對於每個N,輸出N的階乘,佔一行。

Sample Input

1
2
3

Sample Output

1
2
6

程式碼:

#include <stdio.h>

int main()
{
	int i, j,k;
	int N;
	while(~scanf("%d/n",&N))
	{
		int a[50000];//用陣列存值,階乘的值為大數
		memset(a,0,sizeof(a)); //陣列初始化
		a[0] = 1;
		int digit = 1;// 結果的位數
		int up =0; //進位 
		int temp; 
		for(i = 2; i <= N; i++)   //求階乘  
		{
			for(j = 0; j < digit; j++) //當前值的每一位乘階乘的數,例如13*8->3*8->1*8+2
			{
				temp = a[j] * i + up;
				a[j] = temp % 10;
				up = temp / 10;
			}
			while(up)                 //如果最高位有進位,將最高位存入
			{
				a[digit] = up % 10;
				up = up / 10;
				digit++;
			}
		}
		for(i = digit - 1; i >= 0 ;i--) 
		{
			printf("%d",a[i]);
		}
		printf("\n");
	}
}