阶乘,大数问题

#include <iostream>
#include <cmath>
using namespace std;
const int Maxsize=100000;//结果的最大长度
int result[Maxsize],n,resultLength,*tempResult,tempResultLength;
void stand()
{//每次运算后对结果进行标准化,即满十进1
	int i;
	for(i=1;i<tempResultLength-2;i++)
	{
		if(tempResult[i]>9)
		{
			tempResult[i+1]+=tempResult[i]/10;
			tempResult[i]%=10;
		}
	}
}
int getResultLength()
{//得到结果长度
	int i;
	for(i=n*n-1;i>=0;i--)
	{
		if(result[i]!=0)
			break;
	}
	return i+1;
}
int getValueLength(int a)
{
	int i=0;
	while(a)
	{
		a/=10;
		i++;
	}
	return i;
}
void copyResult()
{//复制最后的结果
	int i;
	for(i=0;i<=tempResultLength;i++)
	{
		result[i]=tempResult[i];
	}
}
void fun()
{//大数乘法主要函数
	int i,j,k;
	for(k=1;k<=n;k++)
	{//数值
	
		int tempK=k,valueLength=getValueLength(k);
		tempResultLength=Maxsize;//临时数组的最大长度
		tempResult=new int[tempResultLength];
		for(j=0;j<tempResultLength;j++)
			tempResult[j]=0;//清零
		for(j=1;j<=valueLength;j++)
		{
			int tempELem=tempK%10;
			for(i=1;i<=resultLength;i++)
			{//结果的每一位
				int tempData=result[i]*tempELem;
				tempResult[i+j-1]+=tempData;
				stand();
			}
			tempK/=10;
		}
		copyResult();
		resultLength=getResultLength();
		delete []tempResult;
	}
}
int main()
{
	int i;
	cin>>n;
	if(n==0||n==1)
	{
		cout<<1<<endl;
		return 0;
	}
	for(i=0;i<MaxSize;i++)
		result[i]=0;
	resultLength=1;
	result[1]=1;
	fun();
	for(i=resultLength;i>=0;i--)
		if(result[i]!=0)	break;
	cout<<n<<"!=";
	for(;i>=1;i--)
		cout<<result[i];
	cout<<endl;
	return 0;
}



写完之后才发现搞复杂了,其实可以从小到大开始乘,直到long long的最大范围,后面也这样处理,最后得到m个数(m<n),最后再进行大数处理,这个思路比我写的肯定运行的快,以后有时间再琢磨琢磨吧。

----2014-2-22 15:39

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值