UVA 623 - 500!

本文介绍了一种预先计算所有阶乘的高效算法,并详细解释了如何使用此算法来快速计算给定数值的阶乘。重点突出阶乘计算的时间复杂性和内存需求,以及通过预计算优化性能的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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 orderO(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 ofn!

 

Output

2 lines for each input case. First should contain value ``n" followed by character `!'. The second should contain calculated valuen!.

 

Sample Input

 

10
30
50
100

 

Sample Output

10!
3628800
30!
265252859812191058636308480000000
50!
30414093201713378043612608166064768844377641568960512000000000000
100!
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

 

 

模拟乘法,预先计算好所有阶乘

 

 

#define RUN
#ifdef RUN

#include<stdio.h>
#include<string.h>
const int maxn = 3000;
int f[1000][maxn];
int tmp[maxn];


void printout(){
	for(int i=0; i<1000; i++){
		for(int j=0; j<maxn; j++){
			printf("%d", f[i][j]);
		}
		printf("\n");
	}
}

void init(){
	memset(f, 0, sizeof(f));
	memset(tmp, 0, sizeof(tmp));

	f[0][0] = 1;
	tmp[0] = 1;
	int i;
	for(i = 2; i <= 1000; i++) {
		int c = 0;
		for(int j = 0; j < maxn; j++) {
			int s = tmp[j] * i + c;
			tmp[j] = s % 10;
			c = s / 10;
		}
		memcpy(f[i-1], tmp, sizeof(tmp));
	}

	//printout();
}


int main() {

#ifndef ONLINE_JUDGE
	freopen("623.in", "r", stdin);
	freopen("623.out", "w", stdout); 
#endif

	int i, j, n;
	init();
	
	while(scanf("%d", &n) == 1){

		printf("%d!\n", n);

		if(n == 0){
			printf("1");
		}
		else{
			for(j = maxn-1; j >= 0; j--) if(f[n-1][j]) break;
			for(i = j; i >= 0; i--) printf("%d", f[n-1][i]);
		}

		printf("\n");
	}

	
	return 0;
}


#endif



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值