微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

阶乘,大数问题

#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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐