Tim Varley Logo
Tim Varley Principal AI Engineer and Tech Leader
Problem #16 medium

Power Digit Sum

215=327682^{15} = 32768 and the sum of its digits is 3+2+7+6+8=263 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 210002^{1000}?

View on Project Euler

Implementations

cpp
// Answer: 1366
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
int power_digit_sum(size_t max)
{
std::vector<int> numbers;
numbers.push_back(1);
std::cout << std::endl;
for (size_t i = 0; i < max; i++) {
int carry = 0;
std::for_each(numbers.begin(),numbers.end(),[&carry](int& n){
n *= 2;
n += carry;
carry = ( n >= 10 )?1:0;
n -= (carry * 10);
});
if( 0 != carry ){
numbers.push_back(carry);
}
}
int total = 0;
for (auto itr = numbers.rbegin() ; itr != numbers.rend() ; itr++) {
total += *itr;
}
return total;
}
#if ! defined UNITTEST_MODE
int main(int argc, char const *argv[]) {
std::cout << "Answer: " << power_digit_sum(15) << std::endl;
std::cout << "Answer: " << power_digit_sum(1000) << std::endl;
return 0;
}
#endif // #if ! defined UNITTEST_MODE
View on GitHub
O(n) time complexity

Solution Notes

Mathematical Background

This problem involves computing 210002^{1000}, a 302-digit number, and summing its digits. Direct computation with standard integer types fails since 210002^{1000} exceeds the range of 64-bit integers.

The number of digits in 2n2^n is approximately n×ln2ln10n×0.3010n \times \frac{\ln 2}{\ln 10} \approx n \times 0.3010. For n=1000n = 1000, this gives about 301.0 digits, matching the actual result.

Algorithm Analysis

Big integer multiplication by repeated doubling: Start with 1, then repeatedly multiply by 2 and handle carry when digits exceed 9. Store the number as an array of digits.

Digit-by-digit summation: Convert the final number to a string or iterate through digit array, summing each digit.

Time complexity: O(n) where n=1000 is the exponent. Space complexity: O(d) where d≈301 is the number of digits.

Key Insights

  • Standard integer types cannot hold 210002^{1000} (max unsigned 64-bit is 26412^{64}-1)
  • Array-based arbitrary-precision arithmetic handles very large numbers
  • The result 210002^{1000} has 302 digits and digit sum of 1,366
  • Each doubling operation requires carry propagation through all digits
  • The algorithm scales well for even larger exponents

Educational Value

This problem teaches:

  • Arbitrary-precision arithmetic implementation
  • Array-based number representation
  • Carry propagation in multiplication
  • The limitations of built-in integer types
  • When custom algorithms are needed for large numbers
  • Digit manipulation and summation techniques
  • Exponential growth and its computational implications