蓝桥杯之阶乘计算

【题目描述】
输入一个正整数n,输出n!的值。
其中 n ! = n × ( n − 1 ) × ( n − 2 ) . . . × 1 n!=n\times(n-1)\times(n-2)...\times1 n!=n×(n1)×(n2)...×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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值