1000的阶乘

1000的阶乘

      算出1000的阶乘用到高精度乘法的方法,即先定义一个整形数组,这里我定义它的大小为2570,因为1000的阶乘差位数差不多就是这么大,然后从1开始乘以这2570个元素,若为0则跳过,接着作过位判断,循环1000次即可得到结果。我曾试过用vector容器,每一次进位的都把要进位的数加进容器好像比无谓地跳过0花费的时间更多,它计算1000的阶乘大概要8秒,而这个数组计算则不用1秒的时间。

#include <iostream>
//#include <time.h>
using namespace std;


int result[2566] = {0};

void numUp()
{
	int y;
	int i = 0;
	while(i < 2566)
	{
		if(result[i] > 9)
		{
			y = result[i] / 10;
			result[i] %= 10;
			
			result[++i] += y;
		}
		else
		{
			i++;
		}
	}
}



void fun(int n)
{
	int i = 1, j = 0;
	result[0] = 1;
	for(i = 1; i < n + 1; i++)
	{
		j = 0;
		while(j < 2566)
		{
			if(result[j] == 0)
			{
				j++;
				continue;
			}
			else
			{
				result[j] *= i;
			}
			j++;
		}
		numUp();
	}
}

int main()
{
	/*freopen("in.txt","r",stdin);
	freopen("out.txt", "w", stdout);*/
	int n;
	cin >> n;
	fun(n);
	int i = 2570;
	while(result[i] == 0)
	{
		i--;
	}
	for(; i > -1; i--)
	{
		cout << result[i];
	}
	
	system("pause");
	return 0;
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值