首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

求n的阶乘解决思路

2012-02-27 
求n的阶乘为什么在用堆栈实现n阶乘和递归时只能够算到12啊[解决办法]显然是溢出了,unsigned long最大只能

求n的阶乘
为什么在用堆栈实现n阶乘和递归时只能够算到12啊

[解决办法]
显然是溢出了,unsigned long最大只能到4294927296,自己写个高精度吧,看下面这段程序,算2000的阶乘都没有问题呢:
//阶乘
#include <iostream>
#include <iomanip>
#define max 2000
using namespace std;
long number[max];//高精度数,数组中每项存四位,即用10000进制
int weishu;//保存高精度数的位数除以4
void mul(int m)//高精度乘低精度
{
int i;
for(i=0;i <weishu;i++) number[i]*=m;//先相乘
for(i=0;i <weishu-1;i++) if(number[i]> 9999)//再进位
{
number[i+1]+=number[i]/10000;
number[i]%=10000;
}
while(number[i]> 9999)
{
if(i+1> =max)
{
cout < < "The number is too big!! " < <endl;
exit(2);
}
number[i+1]=number[i]/10000;
number[i]%=10000;
i++;
}
weishu=i+1;
}
void output()
{
cout < <number[--weishu];
while(--weishu> =0) cout < <setw(4) < <setfill( '0 ') < <number[weishu];
cout < <endl;
}
int main()
{
int i,n;
cin> > n;
if(n <1)
{
cout < < "Please input a bigger one! " < <endl;
return 1;
}
weishu=1;
number[0]=1;
for(i=2;i <=n;i++) mul(i);
output();
return 0;
}


[解决办法]
贴下我的n!的源程序(n可以是任意的大数,当然如果数太大,得考虑时间是否耗得起)
/*
**CopyRights, 2007 , NJUPT
**程序名称:大数阶乘
**描述:这是一个计算大数阶乘的算法.
** 主要是通过链表来保存结果的每一位数。
** 这样就不会有像long或int类型时,数太大而导致溢出的情况
**作者:fallwindlotus
**完成日期:2007年3月
*/


/***************************************************************/

#include <iostream.h>
#include <conio.h>

struct Factorial
{
int digit;
struct Factorial *next;
};


void Input(int &n)
{
cout < < "Please the n: ";
cin> > n;
cout < <endl;
}


void Output(struct Factorial *first, int n)
{
struct Factorial *p=first;
struct Factorial *q=p-> next;
int count=0;
if(first-> next!=NULL)//如果链表节点个数大于1,则把链表逆置
{
while(q!=NULL)
{
p-> next=q-> next;
q-> next=first;
first=q;
q=p-> next;
}
}
cout < <n < < "!= " < <endl;
p=first;
while(p!=NULL)//输出
{
count++;
cout < <p-> digit;
p=p-> next;
if(!(count%100)) cout < < " sum= " < <count < <endl;
}
cout < <endl;
}


void FactorialN(struct Factorial* first, int ier)
{
struct Factorial *p=first;
struct Factorial *q=new struct Factorial;
int temp=0;
int flag=1;
int x,y;
do
{
p-> digit=p-> digit*ier+temp;
temp=0;
if (p-> digit> =10)//进位处理
{
if(p-> next!=NULL)//所处理的进位节点不是尾节点
{
temp=p-> digit/10;
p-> digit=p-> digit%10;
}
else//所处理的进位节点是尾节点
{
flag=0;
x=p-> digit/10;
y=p-> digit=p-> digit%10;
while(y> -1)
{
if(x <10)
{
q-> digit=x;
q-> next=NULL;
p-> next=q;
y=-1;
q=new struct Factorial;



}
else
{
q-> digit=x%10;
q-> next=NULL;
p-> next=q;
p=q;
q=new struct Factorial;
x=x/10;
y=x%10;
}
}
}
}
p=p-> next;
}while(p!=NULL&&flag);
delete q;
}

void main()
{
struct Factorial *first=new Factorial;
int n;
first-> digit=1;//链表默认值是1,即0!或1!
first-> next=NULL;
Input(n);
if(n==0||n==1) Output(first,n);
else//n> 2时的阶乘
{
for(int i=1;i <n;i++)
FactorialN(first,i+1);
Output(first,n);
}
cout < < "Press any key to continue! " < <endl;
getch();
}

热点排行