Project Euler Problem 20
阿新 • • 發佈:2018-12-15
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!
#include <iostream>
#include <cassert> // assert()
#include <cstring> // memset()
using namespace std;
class PE0020
{
private:
static const int MAX_DIGITS = 400; // estimation
int m_digitsArray[MAX_DIGITS];
void calculateFactorial(int n);
void adjustDigitsArray();
int getSumOfDigits();
public:
int getSumOfDigitsOfFactorial(int n);
};
int PE0020::getSumOfDigitsOfFactorial (int n)
{
calculateFactorial(n);
return getSumOfDigits();
}
void PE0020::calculateFactorial(int n)
{
memset(m_digitsArray, 0, sizeof(m_digitsArray));
m_digitsArray[0] = 1; // from left to right: unit, decade, hundred,...
for(int i=1; i<=n; i++)
{
for (int j=0; j<MAX_DIGITS; j++)
{
m_digitsArray[j] *= i;
}
adjustDigitsArray();
}
}
void PE0020::adjustDigitsArray()
{
for (int j=0; j+1<MAX_DIGITS; j++)
{
if (m_digitsArray[j] >= 10)
{
m_digitsArray[j+1] += m_digitsArray[j]/10;
m_digitsArray[j] %= 10;
}
}
}
int PE0020::getSumOfDigits()
{
int sumOfDigits = 0;
for(int i=0; i<MAX_DIGITS; i++)
{
sumOfDigits += m_digitsArray[i];
}
return sumOfDigits;
}
int main()
{
PE0020 pe0020;
assert(27 == pe0020.getSumOfDigitsOfFactorial(10));
cout << "The sum of the digits in the number 100! is ";
cout << pe0020.getSumOfDigitsOfFactorial(100) << endl;
return 0;
}