杭电OJ 1042 AC

Problem Description

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.

Sample Input

1

2

3

Sample Output

1

2

6

这道题的关键在于N在10000以内,一般的int行不能存储,这也是大数相加一类的问题。

主要需要解决的问题是数组的位数,下面提供给两种解决方案:

  1. 每一次最高位有进位,位数加一(本人采用这种方法,以下代码已AC)
  2. 不记录位数,最后将数组逆序输出时跳过前面的0,从第一个不为零的数开始输出
#include <iostream>
#include <string.h>
using namespace std;
int main() {
	int a[40000];//一万的阶乘最多不超过40000位,定义一个 40000的数组 
	int n;
	while(cin>>n) {
		//每一次运行循环前将数组元素置零否则会影响下一次循环
		memset(a,0,sizeof(a));
		a[0] = 1;
		int len = 1;
		int temp;
		for(int i = 1; i <= n; i++) {
			int c = 0;  //代表进位标志
			for(int j = 0; j < len ; j++) {
				temp = a[j] * i + c;
				c = temp / 10;
				a[j] = temp % 10;
			}
			while(c!=0) {
				a[len] = c % 10;
				c = c / 10;
				len++;
			}
		}
		for(int i = 0; i < len ; i++) {
			cout<<a[len-1-i];
		}
		cout<<endl;
	}
	return 0;
}
 

猜你喜欢

转载自blog.csdn.net/qq_36552817/article/details/86594876