int - 2147483648~2147483647
long long:-9223372036854775808~9223372036854775807
unsigned int 0~4294967295
unsigned long 0~4294967295
unsigned long long:0~1844674407370955161
而20!(2,432,902,008,176,640,000)就已超过了unsigned long long的上限,10000的阶乘结果为35660位,因此常规的类型变量无法保存我们想要得到的大数阶乘值的,那怎么解决呢?
用数组! int result[int]足矣。别的不多讲了,上代码
/*
author:m_nValue
time:28/03/2011
email:shiweimin1828@163.com
*/
#include <iostream>
#include <math.h>
#include <fstream>
#define N 10000 //10000!
using namespace std;
int *Multi(int *num1, int& size1, int *num2, int size2);
bool NextNum2(int *num2,int size2);
int main()
{
int num1[5]={1,0,0,0,0};//N
int num2[5]={0,9,9,9,9};//N-1
int size1=5;//num1的初始大小
int *bufR;
bufR=Multi(num1,size1,num2,5);
for(int i=1;i<N-1;i++)
{
if(!NextNum2(num2,5))
break;
bufR=Multi(bufR,size1,num2,5);
}
fstream ifs("result.txt",ios::out);//结果导出到文本文件
for(int i=0;i<size1;i++)
{
cout<<bufR[i];
ifs<<bufR[i];
}
ifs.close();
cout<<endl<<endl<<"总共:"<<size1<<endl;
system("pause");
return 0;
}
int *Multi(int *num1, int& size1, int *num2, int size2)
{
int size=size1+size2;
int *pResult=new int[size];
memset(pResult,0,size*sizeof(int));
int count=-1,k,i=0,j=0;
for(i=size2-1;i>=0;i--)
{
count++;
k=count;
for(j=size1-1;j>=0;j--)
pResult[k++]+=num2[i]*num1[j];
}
for(i=0;i<size;i++)
{
if(pResult[i]>=10)
{
pResult[i+1]+=pResult[i]/10;
pResult[i]%=10;
}
}
j=0;
for(i=size-1;i>=0;i--)
{
if(pResult[i]==0)
continue;
else
{
size1=i+1;
break;
}
}
int *temp=new int[size1];
for(i=size1-1;i>=0;i--)
temp[j++]=pResult[i];
delete []pResult;
return temp;
}
bool NextNum2(int *num2,int size2)
{
int nextNum=0;
for(int i=0;i<size2;i++)
{
nextNum+=num2[i]*(int)pow(10.0,(size2-i-1));
}
if(nextNum<=1)
return false;
nextNum-=1;
for(int i=0;i<size2;i++)
{
num2[i]=nextNum/(int)pow(10.0,size2-i-1);
nextNum%=(int)pow(10.0,size2-i-1);
}
return true;
}