Pretty late to the party, but anyway, here is my solution. Sorry in Python, not C ++, but it needs to be relatively easy to translate. And since this is primarily a problem with the algorithm, I hope this is normal.
As for the overflow problem, the only thing that comes to mind is to use arrays of numbers instead of actual numbers. Given this algorithm, I hope this does not affect the performance too much.
https://gist.github.com/frnhr/7608873
He uses these three recursions, which I found by looking and sticking out the problem. Instead, trying to come up with some general and secret equations, here are three examples. From this one can easily see the general case.
ratio 1
Reduces function calls with an arbitrary argument by several recursive calls with more predictable arguments for use in relations 2 and 3.
foo(3456) == foo(3000) + foo(400) + 400 * (3) + foo(50) + 50 * (3 + 4) + foo(6) + 6 * (3 + 4 + 5)
ratio 2
Reduce calls with an argument of the form L*10^M (for example: 30, 7000, 900000) for a recursive call suitable for relation 3. These triangular numbers popped up completely uninvited (but welcome) :)
triangular_numbers = [0, 1, 3, 6, 10, 15, 21, 28, 36]
Only useful if L > 1 . This is true for L = 1 , but trivial. In this case, go directly to ratio 3.
ratio 3
Recursively reduce calls with an argument in the format 1*10^M by a call with an argument divided by 10.
foo(1000) == foo(100) * 10 + 44 * 100 + 100 - 9
Ultimately, you only need to calculate the sum or numbers for numbers from 0 to 10, and it turns out that only up to 3 of these calculations are needed. Everything else will take care of this recursion. I am sure it works in O(logN) time. This is FAAST !!!!! 11one
On my laptop, it calculates the sum of the digits of the sum for a given number with more than 1300 digits in less than 7 seconds! Your test (1000000000000000000) is calculated in 0.000112057 seconds!