Project Euler 题解 #20 Factorial digit sum

题目:Factorial digit sum

n! means n × (n− 1)× ...× 3× 2× 1

For example, 10! = 10 × 9× ...× 3× 2× 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

这个题目就是大数乘法,直接上代码。

代码实现

//https://projecteuler.net/problem=20
//Factorial digit sum

#include <iostream>
#include <string>
#include <cstdio>

using namespace std;

#define  MAX_LEN  1024 //数字串的最大长度

//该函数不能交换同一个地址上的值, 否则, 会将a b置0
template <class T> void Swap(T& a, T& b) 
{
	if (&a == &b)
	{
		return;
	}
	a ^= b ^= a ^= b;
}

void MUL(char str1[], char str2[], char result[])
{
	int len1 = strlen(str1), len2 = strlen(str2);
	int index = 0, carry = 0, temp = 0;;

	for (int i1 = len1 - 1; i1 >= 0; --i1)
	{
		index = len1 - 1 - i1;
		for (int i2 = len2 - 1; i2 >= 0; --i2)
		{
			temp = (result[index] - '0') + (str1[i1] - '0') * (str2[i2] - '0') + carry;

			result[index] = temp%10 + '0';
			carry = temp/10;

			++index;
		}

		if (carry > 0)
		{
			result[index] = (result[index] - '0') + carry + '0';
			carry = 0;
			++index;
		}
	}

	//去掉结果数字串中前面的0
	while (result[index] == '0' && index > 0)
	{
		--index;
	}

	result[++index] = '\0';

	int i =0, j = index - 1;
	while(i < j)
	{
		Swap(result[i], result[j]);
		++i;
		--j;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int N = 100;

	char product[MAX_LEN] = "1";
	for (int i = 1; i <= N; ++i)
	{
		char mult[MAX_LEN] = {0};
		sprintf_s(mult, MAX_LEN, "%d", i);

		char result[MAX_LEN];
		memset(result, '0', MAX_LEN);

		MUL(product, mult, result);

		memcpy_s(product, MAX_LEN, result, MAX_LEN);
	}

	int sum = 0;
	for (int i = 0; i < strlen(product); ++i)
	{
		cout<<product[i];
		sum += product[i] - '0';
	}
	cout<<endl;
	cout<<"sum = "<<sum<<endl;

	system("pause");
	return 0;
}

输出结果:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值