【题目描述】
输入一个正整数n,输出n!的值。
其中
n
!
=
n
×
(
n
−
1
)
×
(
n
−
2
)
.
.
.
×
1
n!=n\times(n-1)\times(n-2)...\times1
n!=n×(n−1)×(n−2)...×1
【解析】
显而易见的大数问题,不用大数做的话直接爆内存。
我用的是字符串模拟进位,之所以没用整形数组是因为不好确定数组长度,还要拿一个变量去记录,而字符串末尾自动补 \0,又有
s
t
r
l
e
n
(
)
strlen()
strlen()函数可以获取长度,很舒服。
注意:别忘了进位可能不止有一位,比如
8
×
15
=
120
8\times15=120
8×15=120,末尾留
0
0
0,而
1
1
1和
2
2
2均进到了高位。
【代码】
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 100000 + 10;
void multiple(char str[], int n)
{
int d = 0;
int length = strlen(str);
for (int i = 0;i < length;i++)
{
int t = n * (str[i] - '0') + d;
str[i] = t % 10 + '0';
d = t / 10;
}
while (d)
{
int t = d;
str[length++] = d % 10 + '0';
d /= 10;
}
}
void output(char str[])
{
int length = strlen(str);
for (int i = length - 1;i >= 0;i--) cout << str[i];
cout << endl;
}
int main()
{
int n;
while (cin >> n)
{
char str[maxn] = "1";
for (int i = 1;i <= n;i++)
multiple(str, i);
output(str);
}
return 0;
}