• + 0 comments

    My C++ solution:

    void extraLongFactorials(int n) {
        vector<int> bigInt;
        
        // Extract digits of n to initialise bigInt
        {
            stringstream ss;
            ss << n;
            string nString;
            ss >> nString;
            for (char c : nString)
                bigInt.push_back(c - '0');
            --n;
        }
        
        for (; n > 0; --n)
        {
            // Calculate the product of each individual digit of bigInt with n
            vector<int> product;
            for (unsigned int i = 0; i < bigInt.size(); ++i)
                product.push_back(bigInt[i] * n);
            
            // determine new size of bigInt
            {
                size_t prevSize = bigInt.size();
                stringstream ss;
                ss << n;
                bigInt = vector<int>(prevSize + ss.str().length(), 0);
            }
            
            // Add products to bigInt one by one
            int sizeDiff = static_cast<int>(bigInt.size() - product.size());
            int carryOver = 0;
            for (int j = static_cast<int>(bigInt.size() - 1); j >= 0; --j)
            {
                if (j - sizeDiff < 0)
                {
                    if (carryOver > 0)
                    {
                        bigInt[j] = carryOver % 10;
                        carryOver /= 10;
                    }
                    else
                    {
                        // pop remaining leading 0s, erase() is [first, last)
                        bigInt.erase(bigInt.begin(), bigInt.begin() + j + 1);
                        break;
                    }
                }
                else
                {
                    bigInt[j] = (carryOver + product[j - sizeDiff]) % 10;
                    carryOver = (carryOver + product[j - sizeDiff]) / 10;
                }
            }
        }
        
        for (int i : bigInt)
            cout << i;
    }