利用数组计算n的阶乘(n比较大的情况)和末尾0的个数

//利用数组计算n的阶乘(n比较大的情况)和末尾0的个数
//转自:http://www.cnblogs.com/phinecos/archive/2009/05/03/1448245.html
//简单起见,不考虑负号的情况
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

string add(string num1, string num2)
{//大数加法
	string result = "";
	int len1 = num1.length();
	int len2 = num2.length();
	int nAddOn = 0;//进位
	int i,j,n1,n2,sum;
	vector<char> tmpSum;

	for (i = len1 - 1,j = len2 - 1 ; i >= 0 && j >= 0; --i,--j)
	{
		n1 = num1[i] - '0';
		n2 = num2[j] - '0';
		sum = n1 + n2 + nAddOn;

		if (sum >= 10)
			nAddOn = 1;
		else
			nAddOn = 0;
		tmpSum.push_back(sum % 10 + '0');
	}
	if (len1 > len2)
	{//第一个有剩余
		for (; i >= 0; --i)
		{
			n1 = num1[i] - '0';
			sum = n1 + nAddOn;
			if (sum >= 10)
				nAddOn = 1;
			else
				nAddOn = 0;
			tmpSum.push_back(sum % 10 + '0');
		}
	}
	else if (len2 > len1)
	{//第二个有剩余
		for (; j >= 0; --j)
		{
			n2 = num2[j] - '0';
			sum = n2 + nAddOn;
			if (sum >= 10)
				nAddOn = 1;
			else
				nAddOn = 0;
			tmpSum.push_back(sum % 10 + '0');
		}
	}

	if (nAddOn > 0)
	{
		tmpSum.push_back(nAddOn + '0');
	}
	//因为结果是倒置的,这里需要逆序
	reverse(tmpSum.begin(),tmpSum.end());
	copy(tmpSum.begin(),tmpSum.end(),back_inserter(result));
	return result;
}

string multipy(string num1, string num2)
{//大数乘法,乘法本质上就是加法的累加
	string result = "0";
	int i,j,n1,n2;
	int len1 = num1.length();
	int len2 = num2.length();
	if (len1 < len2)
	{
		for (i = len1 -1; i >=0; --i)
		{
			n1 = num1[i] - '0';
			string sum = "0";
			for (j = 0; j < n1; ++j)
				sum = add(sum,num2);
			string tmpSB(sum);
			for (j = i; j < len1 -1; ++j)
				tmpSB.append("0");

			result = add(result,tmpSB);
		}
	}
	else
	{
		for (i = len2 -1; i >=0; --i)
		{
			n2 = num2[i] - '0';
			string sum = "0";
			for (j = 0; j < n2; ++j)
				sum = add(sum,num1);
			string tmpSB(sum);
			for (j = i; j < len2 -1; ++j)
				tmpSB.append("0");

			result = add(result,tmpSB);
		}
	}

	return result;
}


string factorial(int n)
{
	string result = "1";
	char buff[100];
	for (int i = n; i >= 2; --i)
	{
		result = multipy(result,itoa(i, buff,10));
	}
	return result;
}

int countZero(string res){
	char ch[100];
	int count=0;
	int len=res.length();
	char *p=ch+len-1;
	strcpy(ch,res.c_str());

	while (*p=='0'){
		count++;
		p--;
	}
	return count;
}

int func(int n){
	if(n>0 && n<5)
		return 0;
	else{
		int k=n/5;
		return k+func(k);
	}
}

int main()
{
	int N;
	cin >> N;
	int count;

	string str=factorial(N);
	cout << str.c_str() << endl;
	count=countZero(str);
	cout << count << endl;
	cout << func(N) << endl;

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值