My code seems to work fine as I carefully step through it in the debugger, but I have a mistake I can't find. Does someone see it?
As far as my approach goes, I realize I could download a big number library, but I wanted to use my own base operations instead. I had used a ten base strategy for a previous problem, and half way through it I realized it would have been better if it instead used a large number base instead.
#include <iostream>
#include <vector>
#include <algorithm>
void factorialExpansion(unsignedint& nextN, unsignedint base, unsignedlonglong& power16, std::vector<unsignedlonglong>& factorial);
int main() {
// limit!
constunsignedint limit = 100;
std::vector<unsignedlonglong>factorial = { 1 };
unsignedint base = 0;
{
unsignedint nextN = limit;
unsignedint carry = 0;
unsignedlonglong power16 = static_cast<unsignedlonglong>(pow(10, 16));
while (nextN > 1) {
factorialExpansion(nextN, base, power16, factorial);
nextN--;
}
}
// sum factorial digits
unsignedint 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(unsignedint& nextN, unsignedint base, unsignedlonglong& power16, std::vector<unsignedlonglong>& 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
unsignedint carry = static_cast<unsignedint>(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;
}
}
}
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Sum of digits = 648
What happens if your line 45 logical statement is false? You aren't at present multiplying the higher parts of the factorial, so your overall factorial will end up too small.
Your lines 42 to 61 should roughly parallel my lines 38 to 47, the only difference being that you are working to base "power16" and I was working to base 10. I guess you can, in principle, do most loops by recursion - but I'm not sure that it's helping you here.
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Sum of digits = 648
@meden, if you want to, you can use your 10^16 base instead as below. Outputting the factorial and adding the digits becomes more tricky, that's all.