1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
#include <vector>
#include <algorithm>
void factorialExpansion(unsigned int& nextN, unsigned int base, unsigned long long& power16, std::vector<unsigned long long>& factorial);
int main() {
// limit!
const unsigned int limit = 100;
std::vector<unsigned long long>factorial = { 1 };
unsigned int base = 0;
{
unsigned int nextN = limit;
unsigned int carry = 0;
unsigned long long power16 = static_cast<unsigned long long>(pow(10, 16));
while (nextN > 1) {
factorialExpansion(nextN, base, power16, factorial);
nextN--;
}
}
// sum factorial digits
unsigned int sum = 0;
while (base < factorial.size()) {
while (factorial[base] >= 1) {
sum += factorial[base] % 10;
factorial[base] /= 10;
}
base++;
}
std::cout << "Answer: " << sum << std::endl;
std::cout << std::endl;
}
void factorialExpansion(unsigned int& nextN, unsigned int base, unsigned long long& power16, std::vector<unsigned long long>& factorial) {
// multiply current base
factorial[base] *= nextN;
// if current base becomes too large
if (factorial[base] > power16) {
// pop off the largest part, and save it in carry
unsigned int carry = static_cast<unsigned int>(factorial[base] / power16);
factorial[base] %= power16;
// if next base does not yet exist, create it and put carry inside
if (base + 2 > factorial.size()) {
factorial.push_back(carry);
}
// if next base exists, continue multiply operation on it before adding carry
else {
base++;
factorialExpansion(nextN, base, power16, factorial);
factorial[base] += carry;
}
}
}
| |