HDOJ 1042 N! 大数阶乘
原题 : Problem 1042
http://acm.hdu.edu.cn/showproblem.php?pid=1042
题意:计算n!,这里n<= 10000
分析:很明显的一道大数题,就算用long double 也会数据溢出,因为10000!有30000多位数,所以这里开一个40000大的int数组,其做法就是用数组存储每一位数,用数字乘数组,结果保存在数组里,形成一个循环。
假如存储位数的数组为num[],每个存储的结果应该是 int 结果 = num[i] * n + 进位数。
把个位数存在num中, 就是 num[i] = 结果 % 10;
而进位数就是, 进位数 = 结果 / 10;
这里提供两种做法。C++ and C#
PS :
C++这里全部用指针,本人比较喜欢和习惯用指针,反而用数组做不出。汗,(#--).
C# 这里使用了C#4.0中的BigInteger结构,需要引用System.Numerics.
C++实现
#include <iostream>
#include <cstdio>
#define M 40005
using namespace std;
int main()
{
int n = 0;
while(scanf("%d",&n) != EOF)
{
int num[M]={1};
int *np = num;
int len = 1;
if(n == 0 || n == 1)
{
cout << "1" << endl;
continue;
}
for(int i=2; i<=n; i++)
{
int k = len;
np = num;
while(k--) // 数字乘于数组的每位数
(*np++) *= i;
np = num;
k = 0;
while(k++ <= len) // 进位
{
if(*np / 10 > 0)
{
*(np+1) += *np / 10;
(*np) %= 10;
if(np == num + len - 1) //到达最后一位,长度+1;
{
if(*(np+1) / 10 > 0)//如果最后一位还可以进位,长度+1;
len++;
len++;
}
}
np++;
}
}
for(int i=len-1; i>=0; i--)
printf("%d",num[i]);
printf("\n");
}
return 0;
}
C#实现
using System;
using System.Numerics;
namespace ConsoleApplication2 {
class Program {
static void Main(string[] args)
{
BigInteger [] num = new BigInteger[10005];
num[0] = num[1] = BigInteger.Parse("1");
for (int i = 1; i <= 10000; i++)
num[i] = num[i - 1] * i;
while (true)
{
string str = Console.ReadLine();
if (str == null) break;
int x = Convert.ToInt32(str);
Console.WriteLine(num[x]);
}
}
}
}