题目描述
我们都知道如何计算一个数的阶乘,可是,如果这个数很大呢,我们该如何去计算它并输出它?
输入
输入文件第一行有一个整数n(1≤n≤50),一下n行每行有一个整数k(k大于0小于5000)。
输出
输出文件有n行,各包含一个结果。
样例输入
2
5
50
样例输出
120
30414093201713378043612608166064768844377641568960512000000000000
题意
求 N的阶乘。但N可能很大超过long long int 类型。
思路
1: 各位拆分。
2: 各位进行阶乘。
3 : 每次都从各位开始乘满十进一。
4: 从高位到低位输出 。
代码
#include <iostream>
using namespace std;
int main()
{
int n,m;
cin >> m; //输入m 代表m组测试数据
while(m--)
{
cin >> n;
int a[100001];
int i,j;
int count=1,next=0,mut; //mut乘积 next进位 count位数
a[0]=1;
for (i=2; i<=n; i++)
{
for (j=1; j<=count; j++)
{
mut=a[j-1]*i+next; //每位乘积等于该位当前乘积加进位数
a[j-1] = mut%10; //当前位只能保留一位数
next = mut/10; //下一位应加的进位数
}
while (next)//next>0 //所剩的应进位数不为0说明总位数不足
{
count++; //总位数加一 直至应进位数为零
a[count-1] = next%10;//同上“当前位只能保留一位数”
next = next/10;//同上 “下一位应加的进位数”
}
}
for (i=count-1; i>=0; i--)
cout << a[i]; //从高位到低位输出
cout << endl;
}
return 0;
}